Update ItemsControl when an item in an ObservableCollection is updated

后端 未结 1 1087
难免孤独
难免孤独 2021-02-19 23:33

The Problem:

  • You declare an ItemsControl ( or a control derived from ItemsControl) in the view.
  • You bind the
相关标签:
1条回答
  • 2021-02-20 00:08

    I found the answer using Snoop to debug XAML.

    The issue is that you are trying to bind to the ToString() method and that does not raise the PropertyChanged event. If you look at the XAML bindings you will notice that the ObservableCollection is actually changing.

    Snoop Showing Correct Binding

    Now look at each item control and it's texts binding in the "Text" property. There are none, it's just text.

    Snoop showing no data binding to elements in the items control

    To fix this simply add an ItemsControl ItemTemplate with a DataTemplate that contains the elements you'd like to be displayed.

    <ItemsControl Grid.Row="1" ItemsSource="{Binding Path=Employees, UpdateSourceTrigger=PropertyChanged}" BorderBrush="Red" BorderThickness="1" >
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock>
                    <TextBlock.Text>
                        <MultiBinding StringFormat=" {0} is {1} years old">
                            <Binding Path="Name"/>
                            <Binding Path="Age"/>
                        </MultiBinding>
                    </TextBlock.Text>
                </TextBlock>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    

    We now have a green light on binding. RaisePropertyChanged is being called.

    Binding correctly shows green

    Ta-da!

    Solution shown

    0 讨论(0)
提交回复
热议问题