首页 > 解决方案 > WPF ComboBox不显示所选值

问题描述

我已经设法绑定 ItemsSource 和 ComboBox 让我选择每个选项,但我看不到选择了哪个选项。ComboBox 只是空白。XAML 代码:

<ComboBox
  Name="Position"
  Grid.Row="5"
  SelectedValue="{Binding Position}"
  ItemsSource="{Binding Positions}"
  Style="{StaticResource MaterialDesignComboBox}"
  Margin="15,10,15,10"
  FontSize="12"/>

尝试了基本的 ComboBox(非材料设计),结果是相同的。

如果您需要,我会提供更多代码,但到目前为止,该控件似乎刚刚损坏,它无法正常工作。我可能遗漏了一些如何正确设置的小细节。

编辑

视图模型:

public class WindowAddEmployeesViewModel : EmployeesViewModel, INotifyPropertyChanged
{
    public ObservableCollection<PositionsViewModel> Positions { get; set; }

    new public event PropertyChangedEventHandler PropertyChanged;
}

基类包含 FirstName、LastName、Position 等INotifyPropertyChanged未实现的内容,因为 Fody.PropertyChanged 为我做了。

PositionViewModel

public class PositionsViewModel : INotifyPropertyChanged
{
    public string Position { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;

    public override string ToString()
    {
        return $"{Position}";
    }
}

编辑

切换IsEditableTrue使其可见,但我不希望用户能够编辑它。

标签: c#wpfcombobox

解决方案


你误解了SelectedValue. 您可以绑定到SelectedValue而不是SelectedItem. 它与显示的值无关ComboBox

ItemsControl.DisplayMemberPath可以通过在数据模型上设置所需的属性来定义显示的值,但仅限于ItemTemplate未定义时。DisplayMemberPath旨在替换DataTemplate简单场景中的。

你显然想设置DisplayMemberPath.
还有你当前的绑定

<ComboBox SelectedValue="{Binding Position}" .../> 

不会解决(无论 的状态如何ComboBox.IsEditable),因为DataContextofComboBox显然是 theWindowAddEmployeesViewModel而不是PositionsViewModel. 这可能暗示您使用SelectedValue错误。

SelectedItem:当前选择的数据模型。

SelectedValue: 返回 上的属性值SelectedItem,由 定义SelectedValuePath

SelectedValuePath: 设置属性的路径,应该SelectedValueSelectedItem. 参数是一个string.

DisplayMemberPath: 设置每个数据模型上的属性的路径,该属性用于在ComboBox. 参数是一个string.

数据模型

public class PositionsViewModel : INotifyPropertyChanged
{
    public string Label { get; set; }
    public string Position { get; set; }

    public override string ToString() => Position;
}

风景

<!-- Since DisplayMemberPath="Position" the ComboBox will show the value of the Position property as its items -->
<ComboBox x:Name="PositionComboBox"
          DisplayMemberPath="Position"
          SelectedValuePath="Label"
          ItemsSource="{Binding Positions}" />

<!-- 
  Displays the PositionsViewModel. Implicitly invokes PositionsViewModel.ToString().   
  The TextBox will therefore display the property value of `PositionsViewModel.Position`.
 -->
<TextBox Text="{Binding ElementName=PositionComboBox, Path=SelectedItem}" />

<!-- 
  Displays the SelectedValue of the ComboBox. This value is defined by ComboBox.SelectedValuePath.
  The TextBox will therefore display the property value of `PositionsViewModel.Label` 
-->
<TextBox Text="{Binding ElementName=PositionComboBox, Path=SelectedValue}" />

推荐阅读