c# - 显示选定的组合框项目显示名称

标签 c# wpf mvvm

我有一个带有 ValueMember="Id" 的组合框和 DisplayMember="Id"并希望显示所选项目属性 Name在标签中,在 ComboBox 中的某个值之后在选中。我正在使用某种 MVVM pattern .所以,我绑定(bind)SelectedId型号 ItemsSource查看型号 .
(如果我将 ItemsSource 放入 模型 很容易 - 使用 setter 和 OnPropertyChanged() ,但现在我在模型中有很多仅用于 UI 表示的字段)

我已经设法使用组合框 LostFocus 显示所选项目的名称事件,我调用 ViewModel我获得属性(property)的方法Name使用 LINQ(来自列表,
在哪里 l.Id=Model.SelectedId )。

但是,有没有更简单的方法?

最佳答案

您可以直接绑定(bind)到标签的组合框:

     <ComboBox Name="MyCombo" ItemsSource="{Binding ComboListObjects}" SelectedItem="{Binding ComboSelection}" />
        <Label Content="{Binding ElementName=MyCombo, Path=SelectedValue}"/>

但是,由于您使用的是 ViewModel,因此您可能应该稍微改变一下。 Combobox 上没有 SelectedId,所以我假设您的意思是 SelectedValue。相反,我建议在您的 ViewModel 上创建一个属性来保存 SelectedItem。我已经包含了一个示例:

View 模型:
public class MyViewModel : INotifyPropertyChanged
{
   public List<MyObject> ComboListObjects
    { 
        get{
            return new List<MyObject>();  // <-- fill this
        }
    }

    private MyObject _selectedItem = null;
    public MyObject ComboSelection
    {
        get { return _selectedItem; }
        set {
            _selectedItem = value;
            NotifyPropertyChanged("ComboSelection");
        }
    }
}

看法:
    <ComboBox Name="MyCombo" ItemsSource="{Binding ComboListObjects}" SelectedItem="{Binding ComboSelection}" />
    <Label Content="{Binding ComboSelection.Id}"/>
    <Label Content="{Binding ComboSelection.Name}"/>
    <Label Content="{Binding ComboSelection.OtherInfo}"/>

如果您打算使用 MVVM,请避免使用代码隐藏,尤其是事件,除非您正在编写自定义控件。

希望有帮助...

关于c# - 显示选定的组合框项目显示名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8333272/

相关文章:

c# - 排序和交替 ListView

c# - 什么时候在WPF中引发CollectionViewSource.Filter事件?

c# - 我应该如何过滤绑定(bind)到网格的 IReactiveList?

c# - 如何从后面的代码访问我的 ViewModel

c# - ViewModel 中计时器的更好解决方案?

c# - 如何对 URL 字符串进行编码

wpf - 为什么在 Collection 更改时不调用 Converter?

c# - 在 IISExpress 中获取 ASP.Net Core 关闭触发 ApplicationStopping 事件

c# - 官方网站上的 Microsoft Speech Platform Error 404

c# - 登录 Wpf ... 对吗?