I want to create WPF controls in which there are some other controls: The main problem is how to select the right control based on the type of model is?
& lt; MyControl & gt; & Lt ;! - If DataContext.GetType () == Type 1 - & gt; & Lt; Control1 DataContext = {binding} / & gt; & Lt ;! - If DataContext.GetType () == Type 2 - & gt; & Lt; Control2 DataContext = {binding} & gt; & Lt; / MyControl & gt;
How can I apply it and design it well? My idea was to do something like this ...
Control CreateControl (object datacontact) {if (dataContext.GetType () == TYpe1) return new Control1 () {DataContext = dataContext} (DataContext.GetType () == TYpe2) Return new Control2 () () {DataContext = dataContext}}
but I do not know how I can add such a method XAM ...
You can define DataTemplates
in resources, and ContentControl
as a placeholder
Resource: < / P>
& gt; DataTimeplate DataType = "{x: Type Model: Model1}" & gt; & Lt; Control 1 / & gt; & Lt; / DataTemplate & gt; & Lt; DataTemplate DataType = "{x: Type Model: Model2}" & gt; & Lt; Control2 / & gt; & Lt; / DataTemplate & gt;
(Note that you do not need to explicitly set DataContext
)
Usage:
& lt; MyControl & gt; & Lt; Content control content = "{binding}" /> & Lt; / MyControl & gt; Based on the type of content
DataTemplate
.
Comments
Post a Comment