如何向包含组合框列的DataGrid添加行

时间:2014-04-20 04:06:55

标签: c# wpf datagrid

我有一个DataGrid定义如下:

<DataGrid AutoGenerateColumns="False" Height="200" HorizontalAlignment="Left" Margin="44,39,0,0" Name="DataGrid1" VerticalAlignment="Top" Width="277">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Id" />
                <DataGridComboBoxColumn Header="Value" />
            </DataGrid.Columns>
        </DataGrid>

如何将字符串列表绑定到DataGrid并包含项目&#34;是&#34;,&#34;否&#34;,&#34;可能&#34;到每行的DataGridComboboxColumn?

var fruit new List<string> {"Apple","Orange","Banana"};

2 个答案:

答案 0 :(得分:0)

<wpf:DataGridTemplateColumn Width="SizeToHeader" IsReadOnly="True" Header="First Selection">
    <wpf:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding .}"
            Margin="2,0,2,0" HorizontalAlignment="Center" VerticalAlignment="Stretch" />
        </DataTemplate>
    </wpf:DataGridTemplateColumn.CellTemplate>

您可以使用模板列在datagrid中添加复选框

答案 1 :(得分:0)

public class Fruit
{
    public string ID {get;set;}
    public string Name { get; set; }

}

<强> XAML

  <DataGrid AutoGenerateColumns="False" Name="myGrid" Margin="10">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Path=Name}"></DataGridTextColumn>                
            <DataGridComboBoxColumn Width="100" x:Name="Result" SelectedValueBinding="{Binding Result, Mode=TwoWay}" DisplayMemberPath="{Binding Result}"></DataGridComboBoxColumn>
        </DataGrid.Columns>
    </DataGrid>

<强>代码隐藏

public partial class DataGridComboBox : Window
{
    public List<Fruits> Fruits { get; set; }
    public List<string> Result{ get; set; }

    public DataGridComboBox()
    {
        Fruits  = new List<Employee>()
        {
            new Employee() { Name = "Apple", Result= "Yes" },
            new Employee() { Name = "Mango",Result = "No" },
            new Employee() { Name = "Banana",Result ="MayBe" }
        };

        Result= new List<string>();
        Result.Add("Yes");
        Result.Add("No");
        Result.Add("MayBe");
        InitializeComponent();
        myGrid.ItemsSource = Fruits;
        Result.ItemsSource = Result;
    }


}