views:

335

answers:

2

Hi, 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" FontWeight="Bold" />
            <Control Type = "{Binding Control}"/>
       </DockPanel>
</DataTemplate>

Thanks Dan

A: 

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.

Matt Hamilton
A: 

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.

mackenir
I have been trying to get this to work but am coming up short. I would expect the below to show a textbox: public class Person { public string Name { get; set; } public TextBox ControlType = new TextBox(){Text = "test"}; }.<DataTemplate x:Key="PersonTemplate"> <DockPanel > <TextBlock FontWeight="Bold" Text="Name: " DockPanel.Dock="Left" Margin="5,0,10,0"/> <TextBlock Text="{Binding Name}" Foreground="Green" FontWeight="Bold" /> <ContentControl Content="{Binding ControlType}"/> </DockPanel></DataTemplate>
Dan Black
Sorry, lost formatting!! Can re-post if that'l help??
Dan Black
@Dan, in your sample class, I would try making ControlType a 'full-on' C# property rather than a public field.
mackenir
Also, ProTip: take a look in the Output window of Visual Studio for any binding error messages.
mackenir
Thank you. Encapsulating the field worked, would never have guessed that. I assumed a public field had the same visibility as a public property. Now, that I am thinking about it, I guess it does make sense, behind the scenes it is probably <guessing here> doing somthing like invoke(methodName), if its a field this will fail. Thanks again
Dan Black
Yeah, I can't think of any theoretical problem with binding to public fields, but WPF data binding just doesnt support it. I have been hit by that before.
mackenir