简体   繁体   English

WPF将静态对象分配给XAML中的DataContext

[英]WPF assign static object to a DataContext in XAML

I'm in a situation where I have to use a static object as my DataContext . 我处于必须将static对象用作DataContext I have read many posts that recommends a Singleton class instead. 我读过很多推荐Singleton课程的文章。 However, I can't go this route due to design constraint. 但是,由于设计限制,我无法走这条路。

I would like to assign a static object to my control DataContext as follows: 我想为控件DataContext分配一个静态对象,如下所示:

<UserControl.DataContext>
   <local:ViewModelA>
</UserControl.DataContext>

However it keeps telling me it is not usable object because it is not define a public constructor. 但是,它一直告诉我这不是可用的对象,因为它没有定义公共构造函数。

In my static view-model, I have a static constructor but it is not public due to C# constraints. 在我的静态视图模型中,我有一个静态构造函数,但是由于C#约束,它不是公共的。

Thank you 谢谢

You can only assign an instance of a (non-static) class to the DataContext property, not a class. 您只能将(非静态)类的实例分配给DataContext属性,而不是类。

You may however have a binding to a static property SomeProperty of your static class, like: 但是,您可能具有对静态类的静态属性SomeProperty的绑定,例如:

<TextBlock Text="{Binding Path=(local:ViewModelA.SomeProperty)}" />

您还可以将类中的所有内容设为静态,但将实际类设为非静态,这将为您带来与静态相同的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM