0

我很抱歉问这个问题,但我真的是 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}" />

正确的方法是如何做到这一点?

4

1 回答 1

0

Because SelectedValuePath and DisplayMemberPath are paths for the item binding you have to make Val and ValName a property:

public int Val { get; private set; }
public string ValName { get; private set; }
于 2012-07-31T00:25:52.783 回答