Добавьте связанный столбец ComboBox в DataGridColumn во время выполнения - PullRequest
2 голосов
/ 16 марта 2011

Я хотел бы отобразить DataGrid, который будет содержать данные, загруженные из источника данных в DataTable. Столбцы будут отличаться каждый раз, и некоторые из них должны быть представлены с помощью ComboBox.

Как мне настроить DataGridTemplateColumn для столбца, для которого требуется ComboBox, во время выполнения?

Хорошо, это самое близкое, что у меня есть с помощью @Meleak, почти там, просто отображение ключа, а не значения, когда сетка не редактируется.

открытый частичный класс MainWindow: Window { общедоступный словарь MyDictionary {get; задавать; }

public MainWindow()
{
    InitializeComponent();

    //Init Dictionary
    this.MyDictionary = new Dictionary<int, string>();
    this.MyDictionary.Add(1, "Value 1");
    this.MyDictionary.Add(2, "Value 2");
    this.MyDictionary.Add(3, "Value 3");

    DataTable dt = new DataTable();

    DataColumn column = new DataColumn("MyTypeId", typeof(int));
    dt.Columns.Add(column);

    DataRow newRow = dt.NewRow();
    newRow["MyTypeId"] = 1;

    dt.Rows.Add(newRow);

    dataGrid.Columns.Add(GetNewComboBoxColumn("My Type", "MyTypeId", this.MyDictionary));

    this.DataContext = dt;
}

public static DataGridTemplateColumn GetNewComboBoxColumn(string header,
                                                  string bindingPath,
                                                  object itemsSource)
{
    DataGridTemplateColumn comboBoxColumn = new DataGridTemplateColumn();
    comboBoxColumn.Header = header;

    Binding textBinding = new Binding();
    textBinding.Path = new PropertyPath(bindingPath);

    FrameworkElementFactory textBlock = new FrameworkElementFactory(typeof(TextBlock));
    textBlock.SetValue(TextBlock.MarginProperty, new Thickness(3, 3, 3, 3));
    textBlock.SetBinding(TextBlock.TextProperty, textBinding);

    FrameworkElementFactory comboBox = new FrameworkElementFactory(typeof(ComboBox));
    comboBox.SetValue(ComboBox.MarginProperty, new Thickness(1, 1, 1, 1));
    comboBox.SetBinding(ComboBox.TextProperty, textBinding);
    comboBox.SetValue(ComboBox.SelectedValuePathProperty, "Key");
    comboBox.SetValue(ComboBox.DisplayMemberPathProperty, "Value");

    Binding itemsSourceBinding = new Binding();
    itemsSourceBinding.Source = itemsSource;
    comboBox.SetBinding(ComboBox.ItemsSourceProperty, itemsSourceBinding);

    comboBoxColumn.CellTemplate = new DataTemplate();
    comboBoxColumn.CellTemplate.VisualTree = textBlock;
    comboBoxColumn.CellEditingTemplate = new DataTemplate();
    comboBoxColumn.CellEditingTemplate.VisualTree = comboBox;

    return comboBoxColumn;
}

}

1 Ответ

4 голосов
/ 16 марта 2011

Обновление
Вы можете использовать DataGridComboBoxColumn и установить SelectedValueBinding, чтобы заставить его работать так, как вы хотите.Так что просто измените метод, который у вас есть, на этот, и он должен работать

public DataGridColumn GetNewComboBoxColumn(string header,
                                           string bindingPath,
                                           object itemsSource)
{
    DataGridComboBoxColumn comboBoxColumn = new DataGridComboBoxColumn();
    comboBoxColumn.Header = header;
    comboBoxColumn.SelectedValuePath = "Key";
    comboBoxColumn.DisplayMemberPath = "Value";

    Binding binding = new Binding();
    binding.Path = new PropertyPath(bindingPath);
    comboBoxColumn.SelectedValueBinding = binding;

    Binding itemsSourceBinding = new Binding();
    itemsSourceBinding.Source = itemsSource;
    BindingOperations.SetBinding(comboBoxColumn, DataGridComboBoxColumn.ItemsSourceProperty, itemsSourceBinding);

    return comboBoxColumn;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...