Different binding behavior for string[] and List<string>

雨燕双飞 提交于 2020-03-02 00:33:47

问题


I try to understand (without success) why binding behaves differentially when source object is string[] and List<string>. I have two lists, their only difference is ItemsSource - in one case array in second List:

XAML code:

<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Button Content="Modify items" Click="Button_Click"/>
    <StackPanel Orientation="Horizontal">
        <StackPanel.Resources>
            <DataTemplate x:Key="ItemTemplate">
                <TextBlock Text="{Binding}" FontSize="16"/>
            </DataTemplate>
        </StackPanel.Resources>
        <ListView ItemsSource="{Binding ArrayElements}" ItemTemplate="{StaticResource ItemTemplate}" Width="100" Margin="20"/>
        <ListView ItemsSource="{Binding ListElements}" ItemTemplate="{StaticResource ItemTemplate}" Width="100" Margin="20"/>
    </StackPanel>
</StackPanel>

Code behind:

public sealed partial class MainPage : Page, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public void RaiseProperty(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

    public string[] ArrayElements { get; } = new string[] { "Standard", "Standard", "Standard" };
    public List<string> ListElements { get; } = new List<string> { "Standard", "Standard", "Standard" };

    public MainPage() { this.InitializeComponent(); this.DataContext = this; }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        ArrayElements[1] = "Modified one";
        ListElements[1] = "Modified one";
        RaiseProperty(nameof(ArrayElements));
        RaiseProperty(nameof(ListElements));
    }
}

Once I click button, the first list (build upon array) gets refilled with new elements (seems like new ItemsSource), so I can see a little flicker and the change in second element.

The same time in the second list nothing changes - the reference to binding source doesn't change so we don't see the difference on screen (PropertyChange has no effect as no property has been changed) - that's clear.

So why the list where the ItemsSource is set to array behaves different?

Sample to reproduce the issue (though almost whole code is above)


回答1:


It sounds weird to me but i never faced this Problem because i use ElementViewModel objects in an observable collection. Instead of changing the list-item / Array element i Change a property of the ElementViewModel and use the INotifyProperty Change there. It's not the actuall answer to you question but you can work around with this.



来源:https://stackoverflow.com/questions/33608268/different-binding-behavior-for-string-and-liststring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!