簡體   English   中英

更改 ObservableCollection 的 item 屬性時更新視圖

[英]Update view when item's property of ObservableCollection is changed

我有 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 中更改項目的邊框厚度並更新到視圖?

謝謝。

您的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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM