Silverlight更新绑定

时间:2010-08-02 11:31:14

标签: c# .net wpf silverlight

我有带图像和文本块的项目模板。并且文本块绑定到Name属性。一切正常,而我不想更新我的数据。当我在树中设置我的源节点新名称时,我看到旧名称。如何更新项目模板中的文字?

    <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>

3 个答案:

答案 0 :(得分:2)

具有Name属性的类必须实现System.ComponentModel.INotifyPropertyChanged接口,以通知WPF UI属性的值已更改。如下所示:

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));
        }
    }
}

答案 1 :(得分:2)

您的Name属性看起来可能如下所示: -

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

但是,您需要一种方法来通知UI属性已更改,以便UI可以自行更新。这就是INotifyPropertyChanged界面的目的: -

 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
 }

实现此接口后,只要绑定属性发生更改,绑定就会更新UI中的值。

答案 2 :(得分:1)

将“Name”作为依赖属性。它具有内置的changeNotification功能。