如何将XAML(ControlTemplate)转换为Code-Behind

时间:2014-09-14 07:01:13

标签: c# wpf xaml charts devexpress

<dxg:LookUpEdit Margin="5" HorizontalAlignment="Stretch" VerticalAlignment="Center" 
                    ItemsSource="{Binding}"
                    DisplayMember="Name" 
                    AutoPopulateColumns="False">
    <dxg:LookUpEdit.PopupContentTemplate>
        <ControlTemplate>
            <dxg:GridControl Name="PART_GridControl">
                <dxg:GridControl.Columns>
                    <dxg:GridColumn FieldName="Name"/>
                    <dxg:GridColumn FieldName="Date"/>
                </dxg:GridControl.Columns>
            </dxg:GridControl>
        </ControlTemplate>
    </dxg:LookUpEdit.PopupContentTemplate>
</dxg:LookUpEdit>

请帮助我,我不知道如何在GridColumn上添加GridControl并设置LookUpEdit.PopupContentTemplate = GridControl

非常感谢你。我认为XAMLREADER可以帮助我,我被困在这里

ControlTemplate ct = new ControlTemplate();
FrameworkElementFactory gridcontrol = new FrameworkElementFactory(typeof(GridControl));
FrameworkElementFactory gridcolumn = new FrameworkElementFactory(typeof(GridColumn));
gridcontrol.SetValue(?, ?);
gridcolumn.SetValue(?, ?);
ct.VisualTree = gridcontrol;

1 个答案:

答案 0 :(得分:1)

在代码后面创建控件/数据模板涉及工厂类,对于非框架类型可能更复杂。

来自Creating a control template with code behind

的示例
ControlTemplate template = new ControlTemplate(typeof(ListBoxItem));
FrameworkElementFactory elemFactory = new FrameworkElementFactory(typeof(Border));
elemFactory.Name = "Border";
elemFactory.SetValue(Border.CornerRadiusProperty, new CornerRadius(5));
elemFactory.SetValue(Border.PaddingProperty, new Thickness(1));
elemFactory.SetValue(Border.SnapsToDevicePixelsProperty, true);
template.VisualTree = elemFactory;

//same can be used as 
LookUpEdit.PopupContentTemplate = template;

上面只是一个例子,您可能需要使用适当的类型

或者将控制模板保存在资源字典中可以帮助您

或最简单的解决方案是在后面的代码中解析xaml

const string xaml = "<ControlTemplate><dxg:GridControl Name=""PART_GridControl""><dxg:GridControl.Columns><dxg:GridColumn FieldName=""Name""/><dxg:GridColumn FieldName=""Date""/></dxg:GridControl.Columns></dxg:GridControl></ControlTemplate>";
ControlTemplate template = XamlReader.Parse(xaml) as ControlTemplate;

//this can be used as 
LookUpEdit.PopupContentTemplate = template;