我有一个带有组合框的WPF项目,我试图绑定到ComboboxItem
个对象列表。 ComboboxItem
是我为示例项目创建的类。这部分工作......我的三个项目可用于组合框,但显示的值为空白,combobox.SelectedValue
的值为空。我已经看过几篇关于如何执行此操作的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;
}
答案 0 :(得分:1)
更改
public class ComboboxItem
{
public string DisplayValue;
public string InternalValue;
}
到
public class ComboboxItem
{
public string DisplayValue {get;set;}
public string InternalValue {get;set;}
}