我有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>
后台代码:
private readonly ObservableCollection<Item> ObjectList = new();
public class Item
{
public Thickness BorderThickness { get; set; }
}
当我做ObjectList.Add(new Item(){BorderThickness = new(10)})
时,它将按预期创建一个borderthickness = 10的网格。现在我想将item的边框厚度更改为100,我执行ObjectList[0].BorderThickness =new(100)
,但它不起作用,视图没有更新。
所以,我的问题是如何在ObservableCollection中更改项目的边框厚度并更新到视图?
谢谢。
您的Item
类必须实现INotifyPropertyChanged,并在厚度值发生变化时引发事件。例如:
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));
}
}
然后,确保将绑定模式设置为OneWay,因为默认情况下它是OneTime。