【问题标题】:Databinding where the data is of type UIElement数据类型为 UIElement 的数据绑定
【发布时间】:2012-11-07 20:18:23
【问题描述】:

我有一个DataGrid 绑定到一个集合视图模型。元素视图模型有一个名为 UI 的属性,类型为 UIElement。场景是我想绑定生成的UIElement

例如(虚构的玩具示例),假设 UIElement 是带有文本 Foo 的 TextBlock,那么我希望 DataGrid 具有带有文本 Foo 的 TextBlock 行。

我想要这个的原因在这里并不重要。

那么如何将数据绑定到UIElement 类型的属性,其中UIElement 作为数据绑定内容注入?

【问题讨论】:

    标签: wpf data-binding virtualization uielement


    【解决方案1】:

    好吧,我猜你可以继续做。

    我相信,这小段代码几乎可以满足您的需求..

    XAML:

    <DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTemplateColumn>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ContentControl Content="{Binding UI}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
    

    代码隐藏:

    public partial class MainWindow : Window
    {
        public List<Model> Items { get; set; }
    
        public MainWindow()
        {
            InitializeComponent();
    
            var textblock = new TextBlock();
            textblock.Text = "I'm a textblock";
    
            var button = new Button();
            button.Content = "I'm a button";
    
            var combobox = new ComboBox();
            combobox.Items.Add("Item1");
            combobox.Items.Add("Item2");
    
            this.Items = new List<Model>(new[] { 
                new Model(textblock),
                new Model(button), 
                new Model(combobox)
            });
    
            this.DataContext = this;    
        }
    
        public class Model
        {
            public UIElement UI { get; set; }
    
            public Model(UIElement ui)
            {
                this.UI = ui;
            }
        }
    }
    

    【讨论】:

    • 完美答案!太感谢了。 :-)
    猜你喜欢
    • 1970-01-01
    • 2016-06-21
    • 2013-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 2018-03-09
    • 2012-08-28
    相关资源
    最近更新 更多