C# 从属属性数据绑定
我尝试将UI绑定到自定义DependencyProperty:C# 从属属性数据绑定,c#,wpf,xaml,data-binding,C#,Wpf,Xaml,Data Binding,我尝试将UI绑定到自定义DependencyProperty: <Window.Resources> <local:Localization x:Key="Localization" xmlns:x="#unknown" xmlns:local="#unknown"/> </Window.Resources> <Grid Name="mainStack" DataContext="{StaticResource Localization}
<Window.Resources>
<local:Localization x:Key="Localization" xmlns:x="#unknown" xmlns:local="#unknown"/>
</Window.Resources>
<Grid Name="mainStack" DataContext="{StaticResource Localization}">
<Button Padding="10,3" Margin="5" Content="{Binding BtnAdd}" Command="New"/>
</Grid>
我的UI元素第一次获取属性值时。但当我使用SwitchLanguage()方法时,属性得到新数据,UI仍然有第一个值
有人能帮我吗
附言。
对不起,为了我的英语
Eugene实际上无法发现任何会导致绑定不更新的错误,但还有一些问题需要解决,DP字段应该是只读的,您不应该为DPs调用任何属性更改通知,因为它们具有内部通知机制(在
SetValue
内)
您确定
MainWindowRes.BtnAdd
的值在SwitchLanguage
中实际上与构造函数中的值不同吗?我尝试了您的示例,似乎一切都正常。但也有一些陷阱:
- 有一个名为本地化的框架类,所以请确保不要混淆李>
- 如何调用
?你必须在正确的情况下调用它!(例如,在代码隐藏中: var res=(本地化)资源[“本地化”];SwitchLanguage()
res.SwitchLanguage()
class Localization : DependencyObject, INotifyPropertyChanged
{
public static DependencyProperty BtnAddProperty;
static Localization()
{
BtnAddProperty = DependencyProperty.Register("BtnAdd", typeof(string), typeof(Localization));
}
public string BtnAdd
{
set
{
SetValue(BtnAddProperty, value);
}
get
{
return (string)GetValue(BtnAddProperty);
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);
handler.Invoke(this, e);
}
}
public Localization()
{
BtnAdd = MainWindowRes.BtnAdd;
}
public void SwitchLanguage()
{
BtnAdd = MainWindowRes.BtnAdd;
OnPropertyChanged("BtnAdd");
}
}