如何绑定集合中的类成员

时间:2012-02-06 12:48:18

标签: c# wpf data-binding collections

我想将我添加到集合中的元素的类成员绑定到DisplayMemberPath。我将ObservableCollection绑定到ComboBox.ItemSource,并希望在组合框列表中显示属性name,该列表是我班AxisBase的成员。
这是我的代码:

private ObservableCollection<AxisBase> axis { get; set; }

axis我用来保存以下类的元素

class AxisBase
{
    ...
    public string name { get; set; }
    ...
}

这就是我的xaml的样子

<ComboBox Name="comboBox_AchsenListe" DisplayMemberPath="{Binding ElementName=axis, Path=AxisBase.name}" ItemsSource="{Binding ElementName=_MainWindow, Path=axis}"</ComboBox>  

有谁知道如何将name绑定到DisplayMemberPath

1 个答案:

答案 0 :(得分:3)

更改DisplayMemberPath值

 DisplayMemberPath="name" 
 SelectedValuePath="name"

并查看此question

我已经为您创建了示例应用程序 这里是xaml

<Window x:Class="ComboBoxSample.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">
<Grid>
    <ComboBox 
            ItemsSource="{Binding Path=AxisBases}" 
            DisplayMemberPath="Name" 
            SelectedValuePath="Name" 
        Height="23" HorizontalAlignment="Left" Margin="200,134,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" />
</Grid>

这里有代码

using System.Collections.ObjectModel;
using System.Windows;

namespace ComboBoxSample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        AxisBases = new ObservableCollection<AxisBase>
                        {
                            new AxisBase {Name = "Firts"},
                            new AxisBase {Name = "Second"},
                            new AxisBase {Name = "Third"}
                        };
        //Set the data context for use binding
        DataContext = this;
    }

    public ObservableCollection<AxisBase> AxisBases { get; set; }
}

public class AxisBase
{
    public string Name { get; set; }
}

}

它工作正常,并且在组合框中的绑定也会显示3个项目。