[英]WPF - Bind combobox to List of custom class objects
我有一個帶有組合框的WPF項目,試圖將其綁定到ComboboxItem
對象的列表。 ComboboxItem
是我為示例項目創建的類。 這部分起作用...我有三個項目可供組合框使用,但是顯示的值為空白, combobox.SelectedValue
值為null。 我已經看過幾篇關於如何做到這一點的stackoverflow文章和其他博客文章。 據我所知,我做的很好。 但是顯然我做錯了。 這是測試項目的源代碼...
XAML:
<Window x:Class="WpfTestApp_ComboBoxes.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
Loaded="Window_Loaded">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="40"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<ComboBox x:Name="cboMyCombo" Grid.Row="0"
SelectionChanged="cboMyCombo_SelectionChanged"></ComboBox>
</Grid>
</Window>
C#代碼隱藏:
public partial class MainWindow : Window
{
List<ComboboxItem> _list = new List<ComboboxItem>();
public MainWindow()
{
_list.Add(new ComboboxItem() { DisplayValue = "One", InternalValue = "1" });
_list.Add(new ComboboxItem() { DisplayValue = "Two", InternalValue = "2" });
_list.Add(new ComboboxItem() { DisplayValue = "Three", InternalValue = "3" });
InitializeComponent();
}
private void cboMyCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0)
{
ComboBox cb = sender as ComboBox;
MessageBox.Show(string.Format("Selected Item: {0}, Selected Value: {1}", cb.SelectedItem, cb.SelectedValue));
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
cboMyCombo.ItemsSource = _list;
cboMyCombo.DisplayMemberPath = "DisplayValue";
cboMyCombo.SelectedValuePath = "InternalValue";
}
}
ComboboxItem類:
public class ComboboxItem
{
public string DisplayValue;
public string InternalValue;
}
更改
public class ComboboxItem
{
public string DisplayValue;
public string InternalValue;
}
至
public class ComboboxItem
{
public string DisplayValue {get;set;}
public string InternalValue {get;set;}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.