繁体   English   中英

WPF ComboBox 不显示所选值

[英]WPF ComboBox not displaying selected value

我已经设法绑定 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;
}

基本 class 包含 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}";
    }
}

编辑

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

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

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

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

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

将无法解决(无论 ComboBox.IsEditable 的ComboBox.IsEditable ),因为ComboBoxDataContext显然是WindowAddEmployeesViewModel而不是PositionsViewModel 这可能暗示您使用SelectedValue错误。

SelectedItem :当前选中的数据 model。

SelectedValue :返回SelectedValuePath SelectedItem

SelectedValuePath :设置属性的路径,应该是SelectedValue上的SelectedItem 参数是一个string

DisplayMemberPath :设置每个数据 model 的属性的路径,该属性用于显示ComboBox中的项目。 参数是一个string

数据 model

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}" />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM