Search code examples
wpfdata-bindingvirtualizationuielement

Databinding where the data is of type UIElement


I have a DataGrid bound to a collection view model. The element view model has a property called UI of type UIElement. The scenario is that I want the generated UIElement to be bound.

So for example (imaginary toy example), say the UIElement is a TextBlock with a text Foo, then I want the DataGrid to have rows of TextBlock's with the text Foo.

The reason why I want this is not important here.

So how might one databind to a property of type UIElement where the UIElement is injected as the databound content?


Solution

  • Well, you can just go ahead and do it I guess.

    This small piece of code pretty much does what you want i believe..

    XAML:

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

    Code-behind:

    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;
            }
        }
    }