开发者

WPF - Databind dynamic control type

开发者 https://www.devze.com 2022-12-10 11:36 出处:网络
I have a Person class. A Person can have an associated control. Can I display the control through data binding?

I have a Person class. A Person can have an associated control. Can I display the control through data binding?

e.g: Name: Bill , Control: TextBox Name: Bob, Control: ComboBox Name: Dan, Control: CheckBox

I have the following xaml in my resource dictionary

<DataTemplate x:Key="PersonTemplate">
        <DockPanel >
            <TextBlock FontWeight="Bold" Text="Name: " DockPanel.Dock="Left" Margin="5,0,10,0"/>
            <TextBlock Text="{Binding FirstName}" Foreground="Green" FontWeight="Bold" />
       </DockPanel>
</DataTemplate>

I would like to add the associated user control to the dockpanel, Can this be done

Something like??

<DataTemplate x:Key="PersonTemplate">
        <DockPanel >
            <TextBlock FontWeight="Bold" Text="Name: " DockPanel.Dock="Left" Margin="5,0,10,0"/>
            <TextBlock Text="{Binding FirstName}" Foreground="Green" FontWei开发者_如何学Cght="Bold" />
            <Control Type = "{Binding Control}"/>
       </DockPanel>
</DataTemplate>

Thanks Dan


This works for me, at least initially:

<ContentControl Content="{Binding Control}"/>

NB: if your UI binds to this property in more than one place, you could get an exception due to the attempt to parent the control in multiple places.


I think you could use a ContentControl in this case:

<ContentControl Content="{Binding Control}" />

That'll just render whatever you give it. If the Person's "Control" property is a WPF control, it'll render that.

0

精彩评论

暂无评论...
验证码 换一张
取 消