【问题标题】:DataGridComboBoxColumn binding to a list of custom classDataGridComboBoxColumn 绑定到自定义类列表
【发布时间】:2015-01-29 18:11:30
【问题描述】:
<DataGridComboBoxColumn x:Name="categoryColumn" Header="Category"     
                                    SelectedValueBinding="{Binding CategoryID}"
                                    SelectedValuePath="CategoryID"
                                    DisplayMemberPath="CategoryName"
                                    Width="200">

categoryColumn.ItemsSource = FetchData.CategoriesList;
 List<FileModel> _files = new List<FileModel>();
        _files.Clear();
        _files.Add(new FileModel
        {
            Filename = "Test.pdf",
            Title = "Test",
            Category = new CategoryModel
            {
                CategoryID = 63,
                CategoryName = "Personal"
            }
        });
        DataGrid.ItemsSource = _files;

作为 WPF 新手,我无法将数据/项目源绑定到 DataGridComboboxCOlumn。这里的组合框根本不可见。 请帮忙。

【问题讨论】:

    标签: c# wpf datagridcomboboxcolumn


    【解决方案1】:

    问题是 DataGrid 的 dataContext 没有被传递到 DataGridComboBoxBolumn.. 因为它们不是同一个可视化树的一部分。

    所以...当您尝试绑定到 DataGrid 中 CategoryModel 的值时...找不到它。

    Here 是解决此问题的一种方法,它使用 ElementStyles 通过使 Column 成为与 DataGrid 相同的可视化树的一部分来转发 dataContext:

    <!—now itemssource will find the correct DataContext-->
    <dg:DataGridComboBoxColumn Header="Current Product"
        SelectedValueBinding="{Binding Path=CurrentProduct}"
          SelectedValuePath="ProductID"
        DisplayMemberPath="ProductName">              
      <dg:DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="ComboBox">
          <Setter Property="ItemsSource" Value="{Binding Path=ProductsInCategory}" />
        </Style>
      </dg:DataGridComboBoxColumn.ElementStyle>
      <dg:DataGridComboBoxColumn.EditingElementStyle>
        <Style TargetType="ComboBox">
          <Setter Property="ItemsSource" Value="{Binding Path=ProductsInCategory}" />
        </Style>
      </dg:DataGridComboBoxColumn.EditingElementStyle>
    </dg:DataGridComboBoxColumn>
    

    您可以使用这种方法,只需让您的 CategoriesList 成为您可以绑定的属性:

    public ObservableCollection<CategoryModel> CategoriesList { get; set; }
    

    然后在您的设置代码中:

    CategoriesList = FetchData.CategoriesList;
    

    (因此在上面的示例中,您会将 ComboBox 的 ItemsSource 绑定到“CategoriesList”,而不是“ProductsInCategory”)

    【讨论】:

      猜你喜欢
      • 2011-09-05
      • 2012-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      相关资源
      最近更新 更多