UWP Combobox的SelectedItem忽略其绑定值

3
为了说明成功和失败的情况,我要使用以下后端。在每种情况下,我都有一组事物,以及一个属性,该属性设置为array.First()。
public class MainPage
{
    public MainPage()
    {
        this.InitializeComponent();

        FirstString = Strings.First();
        FirstItem = Items.First();
    }

    public string FirstString { get; set; }
    public Item FirstItem { get; set; }

    public string[] Strings => new[] {"1", "2", "3", "4"};
    public Item[] Items => new[]
    {
        new Item {Index = 1},
        new Item {Index = 2},
        new Item {Index = 3},
        new Item {Index = 4}
    };
}

public class Item
{
    public int Index { get; set; }
}

因此,绑定结果在SelectedItem中的项目被选择。

    <ComboBox ItemsSource="{x:Bind Strings}" 
          SelectedItem="{x:Bind FirstString}">
        <ComboBox.ItemTemplate>
            <DataTemplate x:DataType="system:String">
                <TextBlock Text="{x:Bind}"/>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

以下是未能选择备用项目的相同代码

    <ComboBox ItemsSource="{x:Bind Items}" 
          SelectedItem="{x:Bind FirstItem}">
        <ComboBox.ItemTemplate>
            <DataTemplate x:DataType="local:Item">
                <TextBlock Text="{x:Bind Index}"/>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

此外,一旦我打开Mode=TwoWay,这将在初始绑定期间清除我的VM中的值。
所以我的问题是,为什么?有什么不同导致这种情况发生?

你的输出窗口显示了什么? - DotNetRussell
你提出了一个非常有趣的问题。我将在以后的面试中使用它 :) - AlexDrenea
1个回答

1
非常有趣的问题。这里是发生的情况。
基本上,你每次返回一个新的Items集合而不是缓存它。由于Items getter被调用两次,一次来自ItemsSource Binding,一次来自FirstItem binding,所以集合被实例化两次。
因为Item是引用类型,两个Item {Index = 1}实例不相等,所以它们不匹配,Selected Item binding就无法工作。对于字符串,它们是值类型,"1"仍然等于"1",即使它们是不同的实例,所以可以工作。
要解决这个问题,你需要缓存并返回相同的Items实例,每次getter被调用时:
public MainPage()
{
    ...
    Items = new Item[] {...};
    ...
    FirstItem = Items.First();
}

public Item[] Items {get;set;}

谢谢Alex。不幸的是,这只是我遇到的问题的简化版本,到目前为止,这还没有解决我的应用程序中的问题。(很快会有后续问题:-)) - AlSki

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接