【问题标题】:Binding to DataGridComboBoxColumn from collection从集合绑定到 DataGridComboBoxColumn
【发布时间】:2011-01-14 14:31:23
【问题描述】:

尝试绑定到 WPF 中的集合,我得到了以下工作:

XAML:

<toolkit:DataGrid Name="dgPeoples"/>

CS:

namespace DataGrid
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1
    {
        private readonly ObservableCollection<Person> personList = new ObservableCollection<Person>();

        public Window1()
        {
            InitializeComponent();

            personList.Add(new Person("George", "Jung"));
            personList.Add(new Person("Jim", "Jefferson"));
            personList.Add(new Person("Amy", "Smith"));

            dgPeoples.ItemsSource = personList;
        }
    }
}

unnessecary 可能,但这里是 Person 类:

namespace DataGrid
{
    public class Person
    {
        public string fName { get; set; }
        public string lName { get; set; }

        public Person(string firstName, string lastName)
        {
            fName = firstName;
            lName = lastName;
        }
    }
}

但我真正需要的是 DataGridComboBoxColumn 中的这个。以下是我的修改:

XAML:

<toolkit:DataGrid Name="dgPeoples" Grid.Row="0" AutoGenerateColumns="False">
    <toolkit:DataGrid.Columns>
        <toolkit:DataGridComboBoxColumn Width="5*"/>
        <toolkit:DataGridComboBoxColumn Width="5*"/>
    </toolkit:DataGrid.Columns>
</toolkit:DataGrid>

C#:

保持不变。

问题现在是我得到空的组合框列!有什么想法可以让它发挥作用吗?

从长远来看,我需要 2 路绑定,双击名字列会弹出组合框,然后包含集合中所有可能名字的选项(即 George、Jim 和 Amy)。

感谢任何帮助!

【问题讨论】:

  • 我怀疑阅读此内容:blogs.msdn.com/vinsibal/archive/2008/10/31/… 是问题所在。我需要在 XAML 中设置 SelectedItemBinding,但由于我的列表是在代码中定义的,我该怎么做?不,我不想在 XAML 中设置它,因为该应用程序的另一部分允许添加人员对象,因此列表一直在变化。

标签: c# wpf data-binding wpfdatagrid datagridcomboboxcolumn


【解决方案1】:

DataGrid 需要设置HeaderItemsSource 属性:

<toolkit:DataGrid Name="dgPeoples" Grid.Row="0" AutoGenerateColumns="False">
    <toolkit:DataGrid.Columns>
        <toolkit:DataGridComboBoxColumn Width="5*"
            Header="First Name"
            ItemsSource="{Binding Path=fName}"/>
        <toolkit:DataGridComboBoxColumn Width="5*"
            Header="First Name"
            ItemsSource="{Binding Path=lName}"/>
    </toolkit:DataGrid.Columns>
</toolkit:DataGrid>

使用DataGridComboBoxColumn.ItemsSourceDataGridComboBoxColumn.ItemsSource doesn't work时,工具包的其中一个版本似乎存在问题。

但是,为Using combo boxes with the WPF DataGrid 创建了一个解决方法。最后,您可能还想看看 Margaret Parsons 的文章More fun with DataGrid

编辑
现在我不太确定上面的代码是否有效。我是凭记忆做到的,并将其他链接作为资源引用。

看看这篇似乎解决了这个问题的 SO 帖子:Problem binding DataGridComboBoxColumn.ItemsSource

【讨论】:

  • 这不起作用。我和以前一样,除了显然他们现在有标题。它是正确的行数,但是是空白的,双击会调出组合框,但这也是空白的。
  • 查看编辑以参考其他应该解决问题的 SO 帖子。
  • 你能帮我看看如何让我的问题适应那个 SO 问题的解决方案吗?因为我在后面的代码中设置了 ItemsSource,所以他在 xaml 中做到了
猜你喜欢
  • 2020-08-14
  • 1970-01-01
  • 2013-04-24
  • 2023-03-07
  • 2015-01-21
  • 2013-09-05
  • 2011-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多