1

我有一个网格视图:

      <GridView xmlns:controls="using:Windows.UI.Xaml.Controls">
        <GridView.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Image Source="{Binding Image}"></Image>
                    <Grid Height="50" Width="50" Background="{Binding Color}"></Grid>
                    <TextBlock FontSize="25" TextWrapping="Wrap" Text="{Binding Name}" Margin="10,10,0,0"/>
                </Grid>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>

这绑定到一个可观察的集合:

   ObservableCollection<KeyItem> Keys = new ObservableCollection<KeyItem>();

   Keys.Add(new KeyItem { Name = "jfkdjkfd" });
   Keys.Add(new KeyItem { Name = "jfkdjkfd" });

   myView.ItemsSource = Keys;

关键是这样的:

public class KeyItem
{
    public string Name { get; set; }
    public ImageSource Image { get; private set; }
    public Brush Color
    {
        get;
        set;
    }
}

如果我在将颜色分配给 itemssource 之前设置颜色,这会很好。

但我还希望能够在分配 KeyItem 后以编程方式更改其颜色属性,并让 Binding 更改颜色。但在这个配置中,这是行不通的。

让这个工作的最佳方法是什么?

4

1 回答 1

5

你的班级需要实现INotifyPropertyChanged. 这就是允许绑定知道何时更新的原因。拥有 observable 集合只会通知与集合的绑定以获得通知。集合中的每个对象也需要INotifyPropertyChanged实现。

注意[CallerMemberName]in的使用NotifyPropertyChanged。这允许具有默认值的可选参数将调用成员的名称作为其值。

public class KeyItem : INotifyPropertyChanged
{
    private string name;
    public string Name 
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
            NotifyPropertyChanged();
        }
    }

    private ImageSource image;
    public ImageSource Image 
    {
        get
        {
            return image;
        }
        set
        {
            image = value;
            NotifyPropertyChanged();
        }
    }

    private Brush color;
    public Brush Color
    {
        get
        {
            return color;
        }
        set
        {
            color = value;
            NotifyPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    // This method is called by the Set accessor of each property. 
    // The CallerMemberName attribute that is applied to the optional propertyName 
    // parameter causes the property name of the caller to be substituted as an argument. 
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
于 2012-12-15T23:18:26.870 回答