C# MVVM 组合框

标签 c# mvvm binding combobox selecteditem

在 XAML 中,我有一个组合框定义为:

<ComboBox x:Name="UsernameComboBox" 
          ItemsSource="{Binding Users}" 
          DisplayMemberPath="Username" 
          SelectedItem="{Binding Path=SelectedName, Mode=TwoWay}"/>

目前,它不显示任何默认选择的项目。

我用列表填充组合框:

public List<User> Users
{
    get
    {
        return _userRepository.RetrieveUsers();
    }
}

public List<User> RetrieveUsers()
{
    _users = (from Users in _db.Users select Users).ToList();

    return _users;
}

正确的用户是组合框的 ItemSource。然后在 XAML 中我定义了 SelectedItem 并将其绑定(bind)到一个名为 Selected name 的属性。

在代码中是这样的:

    private User _selectedName;
    public User SelectedName
    {
        get
        {
            return _selectedName;
        }
        set 
        {
            if (_selectedName == value) return;
            _selectedName = value;
            OnPropertyChanged("SelectedName");
        }
    }

如何让我的组合框在启动时显示一个 selectedItem?

最佳答案

我看到的一个问题是,每次访问 Users 属性时,都会调用 RetrieveUsers() 方法,它会重新运行您的数据库查询。这会扰乱您的 SelectedItem 绑定(bind),它会期望绑定(bind)到 ComboBox 的项目列表保持不变。换句话说,它通过评估 SelectedItem 与绑定(bind)项目集合的相等性来找到所选项目。

你需要查询一次数据库...

public YourClassConstructor()
{
   _users = _userRepository.RetrieveUsers();
   _selectedName = _users[0];
}

public List<User> Users
{
    get
    {
        return _users;
    }
}

这也将确保第一个项目被选中。

关于C# MVVM 组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6126384/

相关文章:

javascript - Chrome 插件中的 Durandal

Android Kotlin - imageUrl 的绑定(bind)适配器 AK(android.widget.ImageView, java.lang.String) 已经存在

WPF - 如何制作自定义边框

wpf - WPF 样式中的绑定(bind)导致莫名其妙的 "Cannot find governing FrameworkElement"错误

WPF TextBox 值不会在 OnPropertyChanged 上更改

c# - 用于 C# 的 WSDL 生成器

c# - 来自 ItemsControl 项目的 RelayCommand 发送者

C# linq 选择列表中的对象查看另一个对象列表

c# - SignedXml CanonicalizationMethod - http ://www. w3.org/2006/12/xml-c14n11

c# - 访问静态资源中的属性