ComboBox不会在DataGridTemplateColumn中显示绑定数据

时间:2017-12-19 05:38:03

标签: c# wpf xaml combobox datagrid

我创建了一个自定义DataGrid,其中定义了组合框的列。我试图将itemsource值提供给组合框,但它不会在运行时填充组合框中的数据。这是C#和XAML代码。

public MainWindow()
{
    InitializeComponent();
    datagrid_additionalinfo.Items.Add(new object());

    datagrid_additionalinfo.DataContext = new ComboboxViewModel();
}
public class ComboboxViewModel
{
    public List<string> Members { get; set; }
    public List<string> Disciplines { get; set; }

    public ComboboxViewModel()
    {
        this.Members = new List<string>
        {
            "Ali", "Mubashar", "Muffassir", "Nitin"
        };

        this.Disciplines = new List<string>
        {
            "Architecture", "Mechanical", "Structure"
        };
    }
}
<DataGrid  Name="datagrid_additionalinfo" Margin="20,0,20,0" IsReadOnly="False" SelectionMode="Single" CanUserAddRows="True" AutoGenerateColumns="False" SelectionUnit="Cell" >

     <DataGrid.Columns>

            <DataGridTemplateColumn Header="Discipline"   Width="100" >
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ComboBox Width="200" ItemsSource="{Binding Disciplines}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

            <DataGridTemplateColumn Header="Members"  Width="100">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ComboBox Width="200" ItemsSource="{Binding Members}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

     </DataGrid.Columns>

 </DataGrid>

如果我错过了什么,请纠正我。非常感谢你。

1 个答案:

答案 0 :(得分:1)

DataGrid列应放在“Columns”标记内:

    <DataGrid ...>
        <DataGrid.Columns>
          <DataGridTemplateColumn Header="Discipline"   Width="100" >
            ...
          </DataGridTemplateColumn>
          <DataGridTemplateColumn Header="Members"  Width="100">
            ...
          </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

而且,如果你喜欢从代码中填充项目,你不需要使用DataContext,只需写:

    public MainWindow()
    {
        InitializeComponent();
        datagrid_additionalinfo.Items.Add(new ComboboxViewModel());            
    }

修改

如果您更喜欢使用DataContext,请创建一个包含所有项目的ViewModel,例如:

public class MainViewModel
{
    public List<ComboboxViewModel> Items { get; set; }

    public MainViewModel()
    {
        Items = new List<ComboboxViewModel>() { new ComboboxViewModel()};
    }
}

然后在xaml中绑定它:

<DataGrid  Name="datagrid_additionalinfo" ItemsSource="{Binding Items}" ...>

并设置DataContext:

public MainWindow()
{
    InitializeComponent();
    datagrid_additionalinfo.DataContext = new MainViewModel(); 
}