在 XAML 中设置根元素的 DataContext,而不使用属性元素语法
我想知道是否可以写这样的东西:
<Window
... xmlns definitions ...
DataContext=<!--Create an instance here-->
></Window>
而不是这样:
<Window
... xmlns definitions ...
>
<Window.DataContext>
<local:CustomViewModel />
</Window.DataContext>
</Window>
我不需要解决方法来达到相同的效果,我只是好奇第一种语法是否可能。我认为情况并非如此,但值得一问。
I was wondering if it's possible to write something like this:
<Window
... xmlns definitions ...
DataContext=<!--Create an instance here-->
></Window>
Instead of this:
<Window
... xmlns definitions ...
>
<Window.DataContext>
<local:CustomViewModel />
</Window.DataContext>
</Window>
I don't need workarounds to achieve the same effect, I'm just curious if the first kind of syntax is possible at all. I don't think that's the case but it's worth asking.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我能清楚地看到这一点的唯一方法是编写您自己的
MarkupExtension
使用Activator.CreateInstance
(或您的 DI 容器)来创建 VM,从而为您提供如下语法:The only way I can see to this cleanly is to write your own
MarkupExtension
that usesActivator.CreateInstance
(or your DI container) to create the VM, thus giving you a syntax like this:DataContext="{x:Static SomeClass.SomeProperty}" 怎么样,然后在 SomeClass:
其中 object 是您要创建的类型。我不确定 x:Static 是否缓存它曾经检索到的对象,但如果没有,这将起作用。您还可以尝试起诉 ObjectDataProvider
它允许您调用方法、构造函数和属性。
How about DataContext="{x:Static SomeClass.SomeProperty}" and then in SomeClass:
Where object is the type you want to create. I am not sure if x:Static caches the object it once retrieved but if not, this would work. You could also try to sue ObjectDataProvider
It allows you to call methods, constructors and properties.