[英]selected value of WPF combobox does not display
我有一個xml文件,如下所示:
<Root>
<Level>
<id>1</id>
<display>Level1</display>
</Level>
<Level>
<id>2</id>
<display>Level2</display>
</Level>
</Root>
我有一個WPF組合框:
<ComboBox x:Name="cmbLevel" HorizontalAlignment="Left" Margin="73,73,0,0" VerticalAlignment="Top" Width="120"
SelectedValuePath="id" SelectedValue="{Binding XPath=/Root/Level/id}"
ItemsSource="{Binding XPath=/Root/Level}"
IsSynchronizedWithCurrentItem="True" />
插入和顯示效果很好,但是問題是當我想用選定的值填充此組合框時。
目前,我有以下內容
private void InitCombo(XDocument xdoc, ComboBox comboBox, string NodeName)
{
var displayItems = from ele in xdoc.Descendants(NodeName)
select new
{
id = (string)ele.Element("id"),
display = (string)ele.Element("display")
};
comboBox.DisplayMemberPath = "display";
comboBox.SelectedValuePath = "id";
comboBox.ItemsSource = displayItems.ToList();
}
然后我將選定的值添加如下:
cmbLevel.SelectedValue = level;
我是否需要添加其他內容以在組合框中顯示所選值? 我需要重新綁定組合框嗎?
感謝您的幫助和時間
您似乎對使用ComboBox
選擇選項有些困惑。 我建議您閱讀MSDN上的“ 如何:使用SelectedValue,SelectedValuePath和SelectedItem”頁以尋求幫助。 在ComboBox
進行選擇的方法有很多,鏈接的文章中都對這些方法進行了明確說明。
從MSDN:
DisplayMemberPath:獲取或設置源對象上的值的路徑,以用作對象的視覺表示。
SelectedValue:獲取或設置通過使用SelectedValuePath獲得的SelectedItem的值。
SelectedValuePath:獲取或設置用於從SelectedItem獲取SelectedValue的路徑。
SelectedItem:獲取或設置當前選擇中的第一項;如果選擇為空,則返回null
另外,為什么還要在代碼和 XAML中設置相同的屬性?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.