我有一个带有 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/