Combobox 设置中的组合框Flyout在再次打开时不显示选定值

Combobox 设置中的组合框Flyout在再次打开时不显示选定值,combobox,windows-store-apps,winrt-xaml,windows-8.1,flyout,Combobox,Windows Store Apps,Winrt Xaml,Windows 8.1,Flyout,这看起来很简单,但对我来说却变成了一场噩梦。一切都很好,我可以选择一个值并将其报告回视图模型 问题: 用户打开“设置”弹出按钮并选择一个值。用户退出弹出按钮。 用户重新打开“设置”弹出按钮,组合框中没有选定值。但该值存在于视图模型中 场景: 设置中的组合框flyout. <ComboBox x:Name="defaultComboBox" SelectedItem="{Binding UserSettings.DefaultAccount, Mode=TwoWay}" ItemsSour

这看起来很简单,但对我来说却变成了一场噩梦。一切都很好,我可以选择一个值并将其报告回视图模型

问题: 用户打开“设置”弹出按钮并选择一个值。用户退出弹出按钮。 用户重新打开“设置”弹出按钮,组合框中没有选定值。但该值存在于视图模型中

场景: 设置中的组合框flyout.

<ComboBox x:Name="defaultComboBox" SelectedItem="{Binding UserSettings.DefaultAccount, Mode=TwoWay}"  ItemsSource="{Binding UserAccounts}" DisplayMemberPath="CustomName">

<interactivity:Interaction.Behaviors>
            <core:EventTriggerBehavior EventName="Loaded">
                <core:InvokeCommandAction Command="{Binding UserAccountComboboxLoadedCommand}" CommandParameter="{Binding ElementName=defaultAccountComboBox}"/>
            </core:EventTriggerBehavior>
            </interactivity:Interaction.Behaviors>
</ComboBox>

我尝试了代码的一个版本,但无法重现该问题。你能提供更多的代码吗?是否对所选项目进行了其他设置

无论如何,ItemsSource中的项目类型与所选项目的项目类型不同。我将尝试将所选项目绑定更改为项目源中的同一类

例如,将该对象类型设为UserAccount,而不是viewmodel属性UserSettings

差不多

    private UserAccount _selectedUserAccount { get; set; }

    public UserAccount SelectedUserAccount
    {
        get { return _selectedUserAccount; }
        set
        {
            if (_selectedUserAccount != value)
            {
                _selectedUserAccount = value;
                OnPropertyChanged("SelectedUserAccount");
            }
        }
    }
编辑:

您可以将加载的事件处理程序添加到组合框中,然后从代码隐藏中找到viewmodel并设置selected item属性

    private void ComboBox_Loaded(object sender, RoutedEventArgs e)
    {
        ComboBox comboBox = sender as ComboBox;
        comboBox.SelectedItem =
            _viewModel.UserAccounts.Where(x => x.UserAccountString ==  _viewModel.SelectedUserAccount.UserAccountString);
    }

只是想弄清楚,您是否在将重新创建ui实例的场景中尝试了此操作?例如,您选择一个值并移动到另一个xaml页面,然后返回到此页面,或者您是否尝试选择一个值,并且该值在组合框中显示为选中状态?我绝对可以提供一个模式更简单的场景。我没有测试导航。如果您正在导航,是否可以在页面上设置NavigationCacheMode=“Enabled”?这是一个SettingsFly,因此没有NavigationCacheMode。我有两个切换按钮,它也坚持数据的变化。我想真正的问题是:组合框在代码中设置时不会显示所选项目,如果所选项目实例与绑定到组合框的集合中包含的实例不同,则可能会出现这种情况,但我会确保在下次打开弹出按钮时从集合中获得正确的实例。这是可行的,不知道为什么SelectedItem绑定不起作用。
    private UserAccount _selectedUserAccount { get; set; }

    public UserAccount SelectedUserAccount
    {
        get { return _selectedUserAccount; }
        set
        {
            if (_selectedUserAccount != value)
            {
                _selectedUserAccount = value;
                OnPropertyChanged("SelectedUserAccount");
            }
        }
    }
    private void ComboBox_Loaded(object sender, RoutedEventArgs e)
    {
        ComboBox comboBox = sender as ComboBox;
        comboBox.SelectedItem =
            _viewModel.UserAccounts.Where(x => x.UserAccountString ==  _viewModel.SelectedUserAccount.UserAccountString);
    }