[英]WPF Combobox DisplayMemberPath
好的,我查看了其他問題,但似乎沒有得到我的答案,所以希望這里有人可以。
很簡單的問題,為什么 DisplayMemberPath 屬性不綁定到項目?
<ComboBox Grid.Row="1" Grid.Column="2" ItemsSource="{Binding PromptList}" DisplayMemberPath="{Binding Name}" SelectedItem="{Binding Prompt}"/>
跟蹤輸出顯示它正在嘗試綁定到持有 IEnumerable 的類,而不是 IEnumerable 中的實際項目。 我對填充組合框而不在 xaml 中添加一堆行的簡單方法感到困惑。
它只是為 itemssource 中的對象調用 ToString()。 我有一個解決方法是:
<ComboBox Grid.Row="1" Grid.Column="2" ItemsSource="{Binding PromptList}" SelectedItem="{Binding Prompt}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
但在我看來,對於這樣一個簡單的任務來說太過分了。 我可以使用相對源綁定嗎?
DisplayMemberPath
指定每個項目的顯示字符串屬性的路徑。 在您的情況下,您將其設置為"Name"
,而不是"{Binding Name}"
。
您沒有綁定到類中的數據,而是告訴它從由成員“name”命名的類成員中獲取數據,因此,如果您的實例有item.Name == "steve"
它試圖從item.steve
獲取數據。
為此,您應該從 MemberPath 中刪除綁定。 將其更改為MemberPath = "Name"
這告訴它從成員 "Name" 獲取數據。 這樣它將調用item.Name
,而不是item.steve
。
您應該將MemberPath="{Binding Name}"
更改為MemberPath="Name"
。 然后它將起作用。
您可以刪除 DisplayMemberPath,然后在 TextBlock 中設置路徑。
DisplayMemberPath 確實適用於沒有 ItemTemplate 的情況。
或者您可以刪除您的 ItemTemplate 並使用 DisplayMemberPath - 在這種情況下,它基本上會為您創建一個 TextBlock。 不建議你兩者都做。
<TextBlock text="{Binding Path=Name, Mode=OneWay}"
或者,您不需要設置 DisplayMemberPath。 您可以在 PromptList 中的對象中包含覆蓋 ToString()。 像這樣:
class Prompt {
public string Name = "";
public string Value = "";
public override string ToString() {
return Name;
}
}
ToString() 將自動被調用並顯示您的類中的 Name 參數。 這適用於組合框、列表框等。
試試這個:
<ComboBox Grid.Row="1" Grid.Column="2" ItemsSource="{Binding PromptList}" SelectedItem="{Binding Prompt}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Content}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
據我所知,
"DisplayMemberPath" 使用反射獲取數據上下文類中的屬性名稱,如果找不到,則不會顯示任何內容。
如果上課
class some_class{
string xxx{ get; }
}
DisplayMemberPath=xxx,將顯示任何值“xxx”
如果您想從數據上下文連接屬性,您需要創建一個項目模板,該模板將顯示在標題和下拉列表中。
<ComboBox.ItemTemplate>
<DataTemplate DataType="employee">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding first_name}" />
<TextBlock Text="" />
<TextBlock Text="{Binding last_name}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
您不能同時設置“DisplayMemberPath”和“ComboBox.ItemTemplate”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.