从代码中添加WPF中的DataGridComboBoxColumn

时间:2014-08-11 17:18:38

标签: c# wpf xaml wpfdatagrid datagridcomboboxcolumn

我想从C#代码中添加WPF中的DataGridComboBoxColumn。我想将组合框与现有的枚举绑定。

这是我在XAML中的DataGrid代码。

            <DataGrid AutoGenerateColumns="False" Height="133" HorizontalAlignment="Left" Margin="33,124,0,0" Name="datagrid1" VerticalAlignment="Top" Width="684" DataContext="{Binding}" 
                 RowHeaderWidth="0"       CellStyle="{StaticResource Body_Content_DataGrid_Centering}" VerticalGridLinesBrush="Gray"  
                      Background="White" RowBackground="#FFE7F6EC" AlternatingRowBackground="#F9F9F9" ColumnHeaderHeight="30" RowHeight="25" GridLinesVisibility="Vertical" VerticalContentAlignment="Center"
                       CanUserReorderColumns="False" CanUserResizeColumns="False" CanUserResizeRows="False" CanUserSortColumns="True" ColumnHeaderStyle="{StaticResource DataGridColumnHeaderStyle}"
                      FontFamily="Tahoma" IsReadOnly="True" SelectionMode="Extended">
            </DataGrid>

正如您所看到的,我最初有一个空的数据网格。我从代码中向此数据网格添加行。对于每一行,我想添加一个DataGridComboBoxColumn。我希望这个组合框与下面的现有枚举绑定:

   public enum Priority : int
    {
        Unknown = 0,
        Primary = 1,
        Secondary = 2,
        Tertiary = 3,
        Independent = 4,
        NA = 5,
    }

我现在有以下代码用DataGridComboBoxColumn添加行。

        DataGridComboBoxColumn c1 = new DataGridComboBoxColumn();
        c1.Header = "Priority";          
        c1.ItemsSource = Enum.GetValues(typeof(Priority));
        c1.Width = new DataGridLength(1.0, DataGridLengthUnitType.Auto);
        dgInsuranceCards.Columns.Add(c1);

        DataGridTextColumn c2 = new DataGridTextColumn();
        c2.Header = "Company";
        c2.Binding = new Binding("Company");
        c2.Width = new DataGridLength(1.0, DataGridLengthUnitType.Auto);
        dgInsuranceCards.Columns.Add(c2);


        foreach (Info Card in Cards) // Loop through List with foreach
        {
            datagrid1.Items.Add(new Info()
            {
                Priority = Card.Priority,
                Company = Card.Company,               
            });
        }

其中Info是一个类,如下所示:

 public class Info
    {
        public int Priority { get; set; }
        public string Company { get; set; }
    }

0 个答案:

没有答案