将xaml模板绑定转换为后面的代码

时间:2013-10-16 12:08:13

标签: c# wpf xaml templates devexpress

我有一个从数据库填充的gridcontrol。此外,在代码中,我向datatable添加了一个checkeditsettings列。我在xaml中创建了一个模板,但我无法在C#中进行转换。在我的下面的代码中,

XAML代码:

  <dxg:GridColumn FieldName="Select"  Fixed="Right"  UnboundType="Boolean">
  <dxg:GridColumn.EditSettings>
   <dxe:CheckEditSettings  />
 </dxg:GridColumn.EditSettings>
  <dxg:GridColumn.CellTemplate>
 <DataTemplate>
   <local:MyCheckEdit 
    IsChecked="False"
    IsEnabled='True'
    Checked="MyCheckEdit_Checked"      
     EnabledChecked="/Images/mark.png" 
     EnabledUnchecked="/Images/markk.png"
     DisabledUnchecked="/Images/marken.png"  >
    </local:MyCheckEdit>
   </DataTemplate>
    </dxg:GridColumn.CellTemplate>
   </dxg:GridColumn>

到目前为止我尝试过:

        GridColumn colselect = new GridColumn();
        ComboBoxEditSettings c = new ComboBoxEditSettings();
        colselect.EditSettings = c;
        DataTemplate template = new DataTemplate();
        template.VisualTree = new FrameworkElementFactory(typeof(MyCheckEdit));
        template.VisualTree.SetBinding(MyCheckEdit.ContentProperty, new Binding("...?"));
        colselect.CellTemplate = template;

我真的在这里堆叠。

1 个答案:

答案 0 :(得分:2)

DataTemplate保留在xaml的Resources部分中,为其命名(x:Key),并在需要时从代码隐藏中引用它:

<dxg:DataGrid x:name="myGrid" >
    <dxg:DataGrid.Resources>
        <DataTemplate x:Key="MyCellTemplate" >
            <local:MyCheckEdit IsChecked="False"
                               IsEnabled='True'
                               Checked="MyCheckEdit_Checked"      
                               EnabledChecked="/Images/mark.png" 
                               EnabledUnchecked="/Images/markk.png"
                               DisabledUnchecked="/Images/marken.png" />
        </DataTemplate>
    </dxg:DataGrid.Resources>

    ...

</dxg:DataGrid>

然后,在您的代码隐藏中:

GridColumn colselect = new GridColumn();
colselect.EditSettings = new ComboBoxEditSettings();
colselect.CellTemplate = myGrid.Resources["MyCellTemplate"] as DataTemplate;