【问题标题】:How to rewrite the same XAML DataBinding in Code如何在代码中重写相同的 XAML DataBinding
【发布时间】:2011-04-19 17:26:05
【问题描述】:

如何在代码中重新创建以下 XAML 数据绑定?除了 DataTemplate 定义之外,我拥有大部分内容。

这是 XAML 中的 DataBinding 示例

    <GridViewColumn Width="140" Header="Name">
        <GridViewColumn.CellTemplate>
            <DataTemplate>
                <TextBox Text="{Binding Path=Label}" />
            </DataTemplate>
        </GridViewColumn.CellTemplate>
    </GridViewColumn>

这是我目前的代码:

return new GridViewColumn()
        {
            Header = header,
            Width = width,
            DisplayMemberBinding = new System.Windows.Data.Binding(bindingProperty)
        };

问题是,我是如何通过代码为DataTemplate设置CellTemplate的?

【问题讨论】:

    标签: c# xaml binding .net-3.5


    【解决方案1】:

    对于任何感兴趣的人,这里是解决方案:

    private GridViewColumn GetGridViewColumn(string header, double width, string bindingProperty, Type type)
        {
            GridViewColumn column = new GridViewColumn();
            column.Header = header;
    
            FrameworkElementFactory controlFactory = new FrameworkElementFactory(type);
    
            var itemsBinding = new System.Windows.Data.Binding(bindingProperty);
            controlFactory.SetBinding(TextBox.TextProperty, itemsBinding);
    
            DataTemplate template = new DataTemplate();
            template.VisualTree = controlFactory;
    
            column.CellTemplate = template;
            return column;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多