Reputation: 389
I have a problem with binding update when binding property is changed. Look at the code below. I will explain my issue in the following example.
public class SettingsControl : INotifyPropertyChanged
{
string _value = "test";
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public SettingsControl() { }
public string Value
{
get { return _value; }
set { _value = value; OnPropertyChanged("Value"); }
}
}
<local:SettingsControl x:Key="Settings"></local:SettingsControl>
<TextBox Height="72" Text="{Binding Value, Mode=TwoWay, Source={StaticResource Settings} }"/>
<TextBlock Text="{Binding Value, Mode=OneWay, Source={StaticResource Settings} }" VerticalAlignment="Top" Width="135" />
<Button Height="100" Click="button1_Click" />
and code behind:
private void button1_Click(object sender, RoutedEventArgs e)
{
SettingsControl settings = new SettingsControl();
settings.Value = "new value";
}
Now, when I change text in TextBox
everything works just fine. New text is shown in TextBlock
.
But if I set new text in code to the settings.Value
nothing happens.
What I suppose to do in order to change settings.Value
in code and affect TextProperty
in TextBlock
.
EDIT: Solution below for those who had the same problem as me:
SettingsControl settings = (SettingsControl)this.Resources["Settings"];
settings.Value = "new value";
Upvotes: 2
Views: 178
Reputation: 564901
In your code behind, you're setting the value on a new instance, not on the instance being used.
Try changing the code behind to:
private void button1_Click(object sender, RoutedEventArgs e)
{
// Set the Value on "this"
this.Value = "new value";
}
That being said, properties on a "Control" are typically handled via making a Dependency Property, not via INotifyPropertyChanged
. This allows them to be set and used correctly in XAML, and participate fully in binding in more scenarios.
Upvotes: 5