我有 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的網格。現在我想將專案的邊框厚度更改為 100,我這樣做 ObjectList[0].BorderThickness =new(100)了,但它不起作用,視圖沒有更新。
所以,我的問題是如何在 ObservableCollection 中更改專案的邊框厚度并更新到視圖?
謝謝。
uj5u.com熱心網友回復:
您的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。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/485881.html
