DependencyProperty data binding
I try to bind my UI to custom DependencyProperty:
<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>
Also I have class "Localization":
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");
}
}
First time my UI element gets my property value. But when I use my method SwitchLanguage(), property gets new data, and UI still have first value.
Can someone help me please?
P.S. Sorry, for my English.
Eugene
I tried your example, everything seems to work.
But there are some pitfalls:
- There's a framework class called Localization, so make sure you don't mix up!
How do you call
SwitchLanguage()
? You have to call this on the right instance! (For example in the Code Behind:var res = (Localization)Resources["Localization"];
res.SwitchLanguage();
Can't really spot any mistake which would make the binding not update, but there are some other things that need to be fixed, the DP field should be readonly and you should not call any property change notifications for DPs as they have an internal mechanism for notifications (inside SetValue
).
Are you sure the value of MainWindowRes.BtnAdd
is actually different in SwitchLanguage
from the value it has in the constructor?
精彩评论