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.
CodePudding user response:
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.