简体   繁体   中英

Update view when item's property of ObservableCollection is changed

I have xaml code

<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. 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.

So, my question is how do I change the item's border thickness in ObservableCollection and update to the view?

Thanks.

Your Item class must implement INotifyPropertyChanged, and raise the event when the value of Thickness changes. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM