[英]Update view when item's property of ObservableCollection is changed
I have xaml code我有 xaml 代码
<ListView x:Name="ListObject"
ItemsSource="{x:Bind ObjectList}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<Grid BorderThickness="{Binding BorderThickness}">
</Grid>
</DataTemplate>
</ListView.ItemTemplate></ListView>
Code-behind:代码隐藏:
private readonly ObservableCollection<Item> ObjectList = new();
public class Item
{
public Thickness BorderThickness { get; set; }
}
when I do ObjectList.Add(new Item(){BorderThickness = new(10)})
, It will create a grid with borderthickness = 10 as expected.当我执行
ObjectList.Add(new Item(){BorderThickness = new(10)})
时,它将按预期创建一个borderthickness = 10 的网格。 Now I want to change the border thickness of item to 100, I do ObjectList[0].BorderThickness =new(100)
, but it doesn't work, the view isn't updated.现在我想将项目的边框厚度更改为 100,我做了
ObjectList[0].BorderThickness =new(100)
,但它不起作用,视图没有更新。
So, my question is how do I change the item's border thickness in ObservableCollection and update to the view?所以,我的问题是如何在 ObservableCollection 中更改项目的边框厚度并更新到视图?
Thanks.谢谢。
Your Item
class must implement INotifyPropertyChanged, and raise the event when the value of Thickness changes.您的
Item
类必须实现 INotifyPropertyChanged,并在厚度值更改时引发事件。 For example:例如:
class Item : INotifyPropertyChanged
{
private Thickness borderThickness;
public Thickness BorderThickness
{
get { return borderThickness; }
set
{
if (borderThickness!= value)
{
borderThickness= value;
OnPropertyChanged(nameof(BorderThickness));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Then, make sure to set the mode of the binding to OneWay, because by default it is OneTime.然后,确保将绑定模式设置为 OneWay,因为默认情况下它是 OneTime。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.