绑定到静态属性 [英] Binding to static property
问题描述
这是具有静态属性的类:
public class VersionManager
{
private static string filterString;
public static string FilterString
{
get {return filterString; }
set {filterString = value; }
}
}
在我的xaml中,我只想绑定静态属性到一个文本框:
< TextBox>
< TextBox.Text>
< Binding Source ={x:Static local:VersionManager.FilterString}/>
< /TextBox.Text>
< / TextBox>
所有编译,但在运行时,我收到以下异常:
无法将属性
'Source'中的值转换为
'System.Windows.Markup.StaticExtension'类型的对象。
对象
中的错误
$ b标记文件中的System.Windows.Data.Binding'
'BurnDisk;组件/ selectversionpagefunction.xaml'
行57位置29.
任何想法我在做错什么?
如果绑定需要双向,您必须提供路径。对静态属性进行双向绑定有一个窍门,只要该类不是静态的:在资源中声明一个类的虚拟实例,并将其用作绑定的源。
< Window.Resources>
< local:VersionManager x:Key =versionManager/>
< /Window.Resources>
...
< TextBox Text ={Binding Source = {StaticResource versionManager},Path = FilterString}/>
I'm having a hard time binding a simple static string property to a text box.
Here's the class with the static property:
public class VersionManager
{
private static string filterString;
public static string FilterString
{
get { return filterString; }
set { filterString = value; }
}
}
In my xaml, I just want to bind this static property to a text box:
<TextBox>
<TextBox.Text>
<Binding Source="{x:Static local:VersionManager.FilterString}"/>
</TextBox.Text>
</TextBox>
Everything compiles, but at run time, I get the following exception:
Cannot convert the value in attribute 'Source' to object of type 'System.Windows.Markup.StaticExtension'. Error at object 'System.Windows.Data.Binding' in markup file 'BurnDisk;component/selectversionpagefunction.xaml' Line 57 Position 29.
Any idea what I'm doing wrong?
If the binding needs to be two-way, you must supply a path. There's a trick to do two-way binding on a static property, provided the class is not static : declare a dummy instance of the class in the resources, and use it as the source of the binding.
<Window.Resources>
<local:VersionManager x:Key="versionManager"/>
</Window.Resources>
...
<TextBox Text="{Binding Source={StaticResource versionManager}, Path=FilterString}"/>
这篇关于绑定到静态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!