简体   繁体   中英

Change inner user control in Silverlight/WPF by a property at design time

I am creating some custom user controls for WPF. This user controls contain custom dependency properties so I can fill them in the designer.

One of this properties is called "InnerUserControlType". This dependency proeprty is a custom enumeration containing some values like TextBox, ComboBox, Label, CheckBox, etc.

I would like to be able to set this property in my XAML pages in the designer and then see the user control change the displayed inner control depending on the property.

How should I implement this? The grid which will contain the inner control in my user control is a normal field, so it cannot be accessed from a static method property (like the dependency properties).

I want it to have it working in the designer so the designers can work easily.

Thanks a lot!

Put a ContentControl in the grid, bind the Content property to the UserControl via relative source

<ContentControl Content="{Binding RelativeSource={RelativeSource FindAnsector,
                                  AncestorType={x:Tyle myNamespace:MyControl}}}"

and make a DataTemplateSelector that will check the value of InnerUserControlType and will return an appropriate data template containing the control that was asked for in the property.

Depending on your scenarios, you might need to make sure the controls in the data template have the right data context. If the data context of the controls should be the same as of the user control, then on the root element in the data template, add relative binding for data context. Something like (for the text box data template):

<TextBox DataContext="{Binding DataContext,
                               RelativeSource={RelativeSource FindAnsector,
                               AncestorType={x:Tyle myNamespace:MyControl}}}"
 ......
</TextBox>

EDIT:

I've noticed only the wpf tag and missed the silverlight one. In Silverlight you don't have ...TemplateSelector properties, so use a converter instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM