首页 文章

在Windows 8 gridview中绑定到ObservableCollection中的更改对象

提问于
浏览
1

我有一个gridview:

<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更改颜色 . 但是在这个配置中,这不起作用 .

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

1 回答

  • 5

    你的类需要实现INotifyPropertyChanged . 这是允许绑定知道何时更新的原因 . 拥有可观察集合仅通知绑定到集合以获得通知 . 集合中的每个对象也需要实现 INotifyPropertyChanged .

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

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

相关问题