获取ComboBox绑定多列列表的SelectedItem

时间:2018-07-17 10:35:14

标签: c# wpf mvvm combobox

我有一个绑定到*.RData 的多列List

它将列表列ComboBox显示为Name

cbo


问题

ItemSource确实返回SelectedItem

对于NameMessageBox.Show(vm.cboVideoQuality_SelectedItem);显示为string,而不是MyProgram.ViewModel+VideoQuality

我尝试使用以下方法过滤High
Name

但是它给出了错误vm.cboVideoQuality_SelectedItem.FirstOrDefault(s => s.Name);


XAML

绑定'char' does not contain definition for NameItem Source

Selected Item

ViewModel

<ComboBox x:Name="cboVideoQuality" 

          ItemsSource="{Binding cboVideoQuality_Items, Mode=TwoWay}"
          DisplayMemberPath="Name"

          SelectedItem="{Binding cboVideoQuality_SelectedItem, Mode=TwoWay}"
          SelectedValuePath="Name"

          HorizontalAlignment="Left" 
          VerticalAlignment="Top" 
          Margin="0,0,0,0" 
          Width="100" />

C#

由于// Item Source // public class VideoQuality { public string Name { get; set; } public string Bitrate { get; set; } } public List<VideoQuality> _cboVideoQuality_Items = new List<VideoQuality>() { new ViewModel.VideoQuality() { Name = "High", Bitrate = "5000K" }, new ViewModel.VideoQuality() { Name = "Medium", Bitrate = "2500K" }, new ViewModel.VideoQuality() { Name = "Low", Bitrate = "500K" }, }; public List<VideoQuality> cboVideoQuality_Items { get { return _cboVideoQuality_Items; } set { _cboVideoQuality_Items = value; OnPropertyChanged("cboVideoQuality_Items"); } } // Selected Item // public string _cboVideoQuality_SelectedItem { get; set; } public string cboVideoQuality_SelectedItem { get { return _cboVideoQuality_SelectedItem; } set { if (_cboVideoQuality_SelectedItem == value) { return; } _cboVideoQuality_SelectedItem = value; OnPropertyChanged("cboVideoQuality_SelectedItem"); } } 不等于selected = "High",我无法检查SelectedItem

它等于Name

MyProgram.ViewModel+VideoQuality

1 个答案:

答案 0 :(得分:2)

您已经使用过SelectedValuePath,当然也应该使用SelectedValue代替SelectedItem

<ComboBox
      ItemsSource="{Binding cboVideoQuality_Items}"
      DisplayMemberPath="Name"
      SelectedValuePath="Name"
      SelectedValue="{Binding cboVideoQuality_SelectedItem}" .../>

请注意,在两个绑定Mode=TwoWay中都是多余的。默认情况下,ItemsSource绑定不是双向的,而SelectedValue绑定是双向的。

我还建议不要在视图模型属性名称中使用绑定目标属性详细信息。例如。 cboVideoQuality_SelectedItem应该只是SelectedVideoQuality。因此,您也可以将其绑定到ListBox的SelectedValue属性,甚至是TextBlock的Text属性,而不会造成太多混乱。