Combobox绑定到数组失败

时间:2012-07-30 21:36:33

标签: wpf binding combobox arraylist

我很遗憾地询问这个问题,但我是WPF的新手,我搜索了几个小时试图找出这个问题的关键。

给出以下代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        List<Data> _Buffer = new List<Data>();
        for (int i = 0; i < 50; i++)
        {
            _Buffer.Add(new Data(i, i.ToString()));
        }

        //Also tried:
        //comboBox1.DataContext = _Buffer.ToArray();
        comboBox1.ItemsSource = _Buffer.ToArray();
        comboBox1.SelectedValuePath = "Val";
        comboBox1.DisplayMemberPath = "ValName";
        comboBox1.UpdateLayout();
        comboBox1.SelectionChanged += new SelectionChangedEventHandler(comboBox1_SelectionChanged);
    }

    void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        MessageBox.Show(((Data)e.AddedItems[0]).ValName);
    }

    struct Data
    {
        public Data(int Val, string ValName)
        {
            this.Val = Val;
            this.ValName = ValName;
        }
        public readonly int Val;
        public readonly string ValName;
    }
}

我想它假设将一个简单的数组绑定到一个组合非常容易,实际上,除了一个小问题之外,它在组合列表中没有显示任何内容。

XAML:

<ComboBox Height="23" HorizontalAlignment="Left" Margin="109,82,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" ItemsSource="{Binding}" />

如何正确地做到这一点?

1 个答案:

答案 0 :(得分:0)

由于SelectedValuePathDisplayMemberPath是项目绑定的路径,因此您必须将ValValName作为属性:

public int Val { get; private set; }
public string ValName { get; private set; }