views:

26

answers:

3

I have item template with image and textblock. And textblock binded to Name property. Everything working fine while i not trying to update my data. When i set to my source node new name in tree i see old name. How to update text inside item template?

    <my:TreeView.ItemTemplate>
        <toolkit:HierarchicalDataTemplate ItemsSource="{Binding Children}">
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding Icon}"  Width="20" Height="20" />
                <TextBlock Text="{Binding Name}"   Height="20" TextAlignment="Center" HorizontalAlignment="Center" />
            </StackPanel>
        </toolkit:HierarchicalDataTemplate>
    </my:TreeView.ItemTemplate>
+2  A: 

Your class with the Name property must implement System.ComponentModel.INotifyPropertyChanged interface to notify to the WPF UI that a property's value has been changed. Something like the following :

class MyClass : System.ComponentModel.INotifyPropertyChanged
{
    private String _name;
    public String Name
    {
        get { return _name; }
        set { _name = value; RaisePropertyChanged("Name"); }
    }

    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
    protected void RaisePropertyChanged(String propertyName)
    {
        System.ComponentModel.PropertyChangedEventHandler temp = PropertyChanged;
        if (temp != null)
        {
            temp(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
        }
    }
}
decyclone
+2  A: 

Your Name property looks probably looks something like this:-

 public class MyClass
 {
    public string Name {get; set; }
 }

However you need a way to notify the UI that a property has changed so that UI can update itself. That is the purpose of the INotifyPropertyChanged interface:-

 public class MyClass : INotfyPropertyChanged
 {
    string _name;
    public string Name
    {
      get {return _name; }
      set { _name = value; NotifyPropertyChanged("Name"); }
    }

    private void NotifyPropertyChanged(string propertyName)
    {
       if (PropertyChanged != null)
         PropertyChanged(this, new PropertyChangedEventArgs(propertyName))
    }
    public event PropertyChangedEventHandler PropertyChanged
 }

With this interface implemented the binding will update the value in the UI whenever the bound property is changed.

AnthonyWJones
+1  A: 

make "Name" as dependency property. It has inbuilt changeNotification feature.

akapoor
Only works if the bound object is a FrameworkElement.
Aurélien Ribon