2010-09-25 79 views
0

我想創建WPF控件,它由幾個其他控件組成。主要問題是如何根據Model的類型選擇權限控制的實現?WPF,Xaml和控件工廠?

<MyControl> 
<!-- if DataContext.GetType() == Type1 --> 
<Control1 DataContext = {Binding}/> 
<!-- if DataContext.GetType() == Type2 --> 
<Control2 DataContext = {Binding}> 

</MyControl> 

我該如何實施和設計它?我的想法是把有什麼樣...

Control CreateControl(object dataContext) { 
if (dataContext.GetType() == TYpe1) 
    return new Control1() {DataContext = dataContext} 
if (dataContext.GetType() == TYpe2) 
    return new Control2() {DataContext = dataContext}  
} 

但我不知道我怎樣才能調用該方法,它返回控制內部XAML ...

回答

3

您可以在資源定義DataTemplates,並使用ContentControl作爲佔位符

資源:

<DataTemplate DataType="{x:Type model:Model1}"> 
    <Control1 /> 
</DataTemplate> 

<DataTemplate DataType="{x:Type model:Model2}"> 
    <Control2 /> 
</DataTemplate> 

(請注意,您不需要明確設置DataContext

用法:

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

它會根據Content的類型挑選合適的DataTemplate