Using data binding on value which is a FrameworkElement
Asked Answered
F

1

7

One of my data sources produces a collection of values which are typed to the following interface

public interface IData
{
    string Name { get; }
    FrameworkElement VisualElement { get; }
}

I'd like to use data binding in WPF to display a collection of IData instances in a TabControl where the Name value becomes the header of the tab and the VisualElement value is displayed as the content of the corresponding tab.

Binding the header is straight forward. I'm stuck though on how to define a template which allows me to display the VisualElement value. I've tried a number of solutions with little success. My best attempt is as follows.

    <TabControl ItemsSource="{Binding}">
        <TabControl.ItemTemplate>
            <DataTemplate>
                <Label Content="{Binding Name}"/>
            </DataTemplate>
        </TabControl.ItemTemplate>
        <TabControl.ContentTemplate>
            <DataTemplate>
                How do I display VisualElement here?
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl> 

I'm still very new to WPF so I could be missing the obvious here.

Fendig answered 2/4, 2010 at 7:43 Comment(0)
B
10

ContentPresenters were made for this. The content template becomes:

        <TabControl.ContentTemplate>
            <DataTemplate>
                <ContentPresenter Content="{Binding VisualElement}" />
            </DataTemplate>
        </TabControl.ContentTemplate>

I tested it with a TextBlock and a TextBox.

Briefs answered 2/4, 2010 at 13:38 Comment(1)
Worked like a champ! Thanks!Fendig

© 2022 - 2024 — McMap. All rights reserved.