簡體   English   中英

WPF ComboBox項(ItemsSource綁定)不可見

[英]WPF ComboBox items (ItemsSource binding) are not visible

我正在嘗試將List<MyClass>綁定到ComboBox 以下是我實現的簡單代碼:

C#

cmbList.ItemsSource = DbMain.GetNameList();

XAML

<StackPanel Grid.Row="0" Orientation="Horizontal" >

    <TextBlock Text="Names:" Margin="5,0,5,0" VerticalAlignment="Center" Width="50" Visibility="Collapsed"/>

    <ComboBox x:Name="cmbList" Width="200" SelectionChanged="cmbList_SelectionChanged"
      DisplayMemberPath="DisplayName" SelectedValuePath="DisplayName" Foreground="Black"/>

</StackPanel>

問題

DbMain.GetNameList()中檢索List<MyClass>值,並在ComboBox綁定,但這些值不可見。 當我從SelectionChanged ,我也可以訪問SelectedItem 唯一的問題是項目不可見。

在此處輸入圖片說明

輸出窗口錯誤

System.Windows.Data Error: 40 : BindingExpression path error: 'DisplayName' property not found on 'object' ''MyClass' (HashCode=804189)'. BindingExpression:Path=DisplayName; DataItem='MyClass' (HashCode=804189); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')

通過使用此綁定表達式,您表示MyClass中有一個名為DisplayName屬性 ,但是在運行時,由於沒有這樣的屬性 -您將DisplayName定義為field ,這就是為什么在您的情況下它會失敗的原因-因此ComboBox是顯示空白項目。

<ComboBox x:Name="cmbList" 
  DisplayMemberPath="DisplayName"

與未處理的異常不同,這種綁定錯誤不會使應用程序崩潰,但是在調試時可以在輸出窗口中找到它們的蹤跡。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM