Flo*_*res 1 windows-8 windows-runtime winrt-xaml windows-store-apps
我有一个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>
Run Code Online (Sandbox Code Playgroud)
这是一个可观察的收集:
ObservableCollection<KeyItem> Keys = new ObservableCollection<KeyItem>();
Keys.Add(new KeyItem { Name = "jfkdjkfd" });
Keys.Add(new KeyItem { Name = "jfkdjkfd" });
myView.ItemsSource = Keys;
Run Code Online (Sandbox Code Playgroud)
关键项是这样的:
public class KeyItem
{
public string Name { get; set; }
public ImageSource Image { get; private set; }
public Brush Color
{
get;
set;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我在将颜色分配给itemssource之前设置颜色,这可以正常工作.
但我希望能够在分配KeyItem之后以编程方式更改颜色属性,并让Binding更改颜色.但是在这个配置中,这不起作用.
什么是让这个工作的最佳方法?
你的班级需要实施INotifyPropertyChanged.这是允许绑定知道何时更新的原因.拥有可观察集合仅通知绑定到集合以获得通知.集合中的每个对象也需要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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1744 次 |
| 最近记录: |