绑定到静态类实例中的属性 [英] Binding to a property within a static class instance
问题描述
我要实现的目标
我有一个WPF应用程序(仅用于测试),我想将标签的文本(内容)绑定到某个位置的属性.想法是,当用户选择其他语言时,将更改此属性值.当属性更改时,我希望标签文本以新值更新.
I have a WPF application (it's just for testing) and I want to bind the text (Content) of a label to a property somewhere. The idea is that this property value will be changed when the user chooses a different language. When the property changes, I want the label text to update with the new value.
我尝试过的事情
我试图为标签值创建一个具有静态属性的静态类.例如:
I tried to create a static class with a static property for the label value. For example:
public static class Language
{
public static string Name = "Name";
}
然后我可以像这样使用XAML将这个值绑定到我的标签上:
I then was able to bind this value to my label using XAML like so:
Content="{Binding Source={x:Static lang:Language.Name}}"
这对于显示名称"的初始值效果很好.问题是,当Name
属性更改时,标签值不会更改.
And this worked fine for showing the initial value of "Name". The problem is, when the Name
property changes the label value doesn't change.
因此,返回到绘图板(Google).然后我发现了这个答案,听起来完全像我所需要的.所以这是我对此的新尝试:
So, back to the drawing board (Google). Then I found this answer which sounded exactly like what I needed. So here was my new attempt at this:
public class Language
{
public static Language Instance { get; private set; }
static Language() { Instance = new Language(); }
private Language() { }
private string name = "Name";
public string Name { get { return name; } set { name = value; } }
}
通过我的绑定将其更改为:
With my binding changed it this:
Content="{Binding Source={x:Static lang:Language.Instance}, Path=Name}"
这仍然会导致相同的问题.
This still results in the same problem.
问题
我在这里想念什么?值更改后如何更新标签?
What am I missing here? How can I get the label to update when the value is changed?
推荐答案
那根本不是一个属性.试试:
That simply isn't a property. Try:
public class Language
{
public static Language Instance { get; private set; }
static Language() { Instance = new Language(); }
private Language() { Name = "Name"; }
public string Name {get;private set;}
}
或带有更改通知:
public class Language : INotifyPropertyChanged
{
public static Language Instance { get; private set; }
static Language() { Instance = new Language(); }
private Language() { }
private string name = "Name";
public string Name
{
get { return name; }
set { SetValue(ref name, value);}
}
protected void SetValue<T>(ref T field, T value,
[CallerMemberName]string propertyName=null)
{
if (!EqualityComparer<T>.Default.Equals(field, value))
{
field = value;
OnPropertyChanged(propertyName);
}
}
protected virtual void OnPropertyChanged(
[CallerMemberName]string propertyName=null)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
这篇关于绑定到静态类实例中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!