【问题标题】:How to bind class member in a collection如何在集合中绑定类成员
【发布时间】:2012-02-27 22:36:12
【问题描述】:

我想将添加到集合中的元素的类成员绑定到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

【问题讨论】:

  • 看看我的答案更新。我举个例子。
  • 非常感谢。我不得不将我的 ObservableCollection 更改为 public,这最终使它工作。只是一些小事弄乱了整个代码:) 谢谢!

标签: c# wpf data-binding collections


【解决方案1】:

更改 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 个项目。

【讨论】:

  • @theknut: The manual,你读了吗?
  • 我试过了,但我什至无法设置元数据。它永远无法加载我的课程并且设计器崩溃。
猜你喜欢
  • 2012-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多