Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concept of "UpdateSourceTrigger" Property, How to use it in WPF?

Tags:

binding

wpf

I have a TextBlock, binded with an Object and when i update property of object its not refleting on UI, Why ?

Code:

In Windows1.xaml

<TextBlock Name="txtName" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" Width="100" Height="20" Margin="12,23,166,218" />

and In Windows.xaml.cs

public partial class Window1 : Window
{
    Employee obj ;
    public Window1()
    {            
        InitializeComponent();
        obj = new Employee();
        obj.Name = "First";
        txtName.DataContext = obj;
    }

    private void btnUpdate_Click(object sender, RoutedEventArgs e)
    {
        obj.Name = "changed";            
    }
}
public class Employee : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private string _name;
    public string Name
    {
        set 
        {
            this._name = value;
            OnPropertyChanged(Name);
        }
        get { return this._name; }
    }

    protected void OnPropertyChanged(string name)
    {

        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {

            handler(this, new PropertyChangedEventArgs(name));

        }

    }        
}
like image 552
Jeevan Bhatt Avatar asked Dec 13 '10 08:12

Jeevan Bhatt


2 Answers

OnPropertyChanged(Name);

should be:

OnPropertyChanged("Name");

otherwise if the name is set to "Kent", you're raising a property changed event saying that the "Kent" property has changed, which obviously doesn't exist.

As for UpdateSourceTrigger, that only applies to the source. The property you've bound is the target, not the source. And it doesn't make sense for a TextBlock to update its source, because there's no way for the user to modify the TextBlock text. A TextBox, on the other hand, would make sense. In that case, UpdateSourceTrigger determines the point at which the text in the TextBox is pushed back to the source property (e.g. as the user types each character, or when they move away from the TextBox).

like image 131
Kent Boogaart Avatar answered Nov 02 '22 23:11

Kent Boogaart


Pass the name of the property as string, instead of the property value, like so:

OnPropertyChanged("Name");
like image 35
thumbmunkeys Avatar answered Nov 02 '22 23:11

thumbmunkeys