簡體   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