我有一个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更改颜色。但是在这个配置中,这不起作用。
让这项工作最好的方法是什么?
答案 0 :(得分:5)
您的课程需要实施INotifyPropertyChanged
。这是允许绑定知道何时更新的原因。拥有可观察集合仅通知绑定到集合以获得通知。集合中的每个对象也需要实现INotifyPropertyChanged
。
请注意[CallerMemberName]
中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));
}
}
}