从代码隐藏向DataGridControl添加列

时间:2016-05-24 12:08:43

标签: c# .net wpf xceed xceed-datagrid

我正在尝试通过代码隐藏在运行时创建并向DataGridControl(Xceed Community Edition)添加一列。该列包括CombobBox作为DataTemplate。这就是我现在所拥有的:

            CellEditor editor = new CellEditor();
            DataTemplate editTemplate = editor.EditTemplate = new DataTemplate();
            FrameworkElementFactory templateCbox = new FrameworkElementFactory(typeof(ComboBox)) { Name = "cmbMain" };
            templateCbox.SetBinding(ComboBox.SelectedValuePathProperty, new Binding("CountryID"));
            templateCbox.SetBinding(ComboBox.DisplayMemberPathProperty, new Binding("Name"));
            templateCbox.SetBinding(ComboBox.ItemsSourceProperty, new Binding("DataContext.Country") { RelativeSource = new RelativeSource() { AncestorType = typeof(Window) } });
            templateCbox.SetBinding(ComboBox.SelectedValueProperty, new CellEditorContext());
            editTemplate.VisualTree = templateCbox;
            Column clmAdditional = new Column() { FieldName = "CountryID", CellEditorDisplayConditions = CellEditorDisplayConditions.Always };
            clmAdditional.CellEditor = editor;
            _dgvMain.Columns.Add(clmAdditional);

ViewModel包含两个DataTables:

public class ViewMode
{
    public DataTable Address { get; set; }
    public DataTable Country { get; set; }

    public ViewMode()
    {
        Address = new DataTable();
        Address.Columns.Add("HouseNumberAdd", typeof(string));
        Address.Columns.Add("City", typeof(string));
        Address.Columns.Add("Date", typeof(DateTime));
        Address.Columns.Add("Used", typeof(bool));
        Address.Columns.Add("CountryID", typeof(int));

        Address.Rows.Add("Random Address 1", "Krakov", DateTime.Now, true, 1);
        Address.Rows.Add("Random Address 2", "Kharkiv", DateTime.Now, true, 2);
        Address.Rows.Add("Random Address 3", "Moscow", DateTime.Now, false, 3);
        Address.Rows.Add("Random Address 4", "Santiago", DateTime.Now, true, 1);

        Country = new DataTable("Country");
        Country.Columns.Add("Name", typeof(string));
        Country.Columns.Add("CountryID", typeof(int));

        Country.Rows.Add("America", 1);
        Country.Rows.Add("Zimbabve", 2);
        Country.Rows.Add("Cayman", 3);
    }
}

现在,我无法对ComboBox.SelectedValueProperty的绑定设置为{xcdg:CellEditorBinding},因为在程序集中找不到CellEditorBinding。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

我在之前的支持服务单中找到了类似请求的以下代码段。

Binding bin = new Binding();
bin.Mode = BindingMode.TwoWay;
bin.Path = new PropertyPath("(0).(1)", Cell.ParentCellProperty, Cell.ContentProperty);
bin.RelativeSource = RelativeSource.Self;

FrameworkElementFactory factory = new FrameworkElementFactory(typeof(ComboBox));
factory.SetValue(ComboBox.SelectedValueProperty, bin);

如果此代码在您的情况下不起作用并且您需要更多帮助,可以发送电子邮件至support@xceed.com