David Ullmer
David Ullmer

Reputation: 167

DependencyProperty Update on child property changes

In my UWP app, I have a Object with a List inside like so:

public partial class Test
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<string> MyList{ get; set; }
}

Now I want a UserControl with a DependencyProperty of type Test in my Page1. It should update a ListView with ItemSoure bound to Test.MyList.

If I add an Item to Test.MyList I want the ListView to refresh and show the new Item, but I haven't figured out how to update a DependencyProperty if only a "child property" changed.

Upvotes: 2

Views: 684

Answers (2)

Romasz
Romasz

Reputation: 29792

DependencyProperty has nothing to do here, for ListView.ItemsSource use a collection that implements INotifyCollectionChanged - a good example here is mentioned before ObservableCollection. Such collection will automatically notify the UI about its changes.

Sample can look like that - in your user control define DP:

public Test MyData
{
    get { return (Test)GetValue(MyDataProperty); }
    set { SetValue(MyDataProperty, value); }
}

public static readonly DependencyProperty MyDataProperty =
    DependencyProperty.Register("MyData", typeof(Test), typeof(TestControl), new PropertyMetadata(null));

In xaml - use binding to set it as source for ListView:

<ListView Header="{x:Bind MyData.Name}" ItemsSource="{x:Bind MyData.MyList}"/>

Once you have this, just use it in your page:

<local:TestControl Grid.Row="0" Grid.Column="0" MyData="{x:Bind FirstTest}"/>
<local:TestControl Grid.Row="0" Grid.Column="1" MyData="{x:Bind SecondTest}"/>

The when you add/remove element in one of the collections in the behind, it should be updated in the UI. Couple of remarks - I've used here OneTime binding, as for the purpose of this sample it's not needed other way. You may also think of implementing INotifyPropertyChanged in your Test class to notify UI about changes to other properties.

Working sample you can check at GitHub.

Upvotes: 2

nuuse
nuuse

Reputation: 109

You should switch to an ObservableCollection, and after you update a property, call mycollection.Refresh()

Upvotes: 1

Related Questions