WPF TextBlock 以多种语言绑定到 ResourceDictionary
WPF TextBlock binding to ResourceDictionary in mutilingual
我有一个多语言的 wpf 项目。我正在使用 ResourceDictionary 来执行此操作。对于静态 TextBlock
我可以通过以下方式更改文本语言:
<TextBlock Text="{Binding Sample, Source={StaticResource Resources}}" />
但是 我应该如何更改动态 TextBlock
文本。这样做好像不行:
<TextBlock Text="{Binding Sample}
后面的代码中:
Sample = Resources.SampleText;
如果这是不可能的。还有其他选择吗?提前致谢!
定义 Sample
属性 的 class 应该实现 INotifyPropertyChanged 接口并引发更改通知:
public class Translations : INotifyPropertyChanged
{
private string _sample;
public string Sample
{
get { return _sample; }
set { _sample = value; OnPropertyChanged("Sample"); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
只有这样,您才能通过简单地将 Sample
源 属性 设置为新的 string
值来动态更新 TextBlock
。
我有一个多语言的 wpf 项目。我正在使用 ResourceDictionary 来执行此操作。对于静态 TextBlock
我可以通过以下方式更改文本语言:
<TextBlock Text="{Binding Sample, Source={StaticResource Resources}}" />
但是 我应该如何更改动态 TextBlock
文本。这样做好像不行:
<TextBlock Text="{Binding Sample}
后面的代码中:
Sample = Resources.SampleText;
如果这是不可能的。还有其他选择吗?提前致谢!
定义 Sample
属性 的 class 应该实现 INotifyPropertyChanged 接口并引发更改通知:
public class Translations : INotifyPropertyChanged
{
private string _sample;
public string Sample
{
get { return _sample; }
set { _sample = value; OnPropertyChanged("Sample"); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
只有这样,您才能通过简单地将 Sample
源 属性 设置为新的 string
值来动态更新 TextBlock
。