2012-05-25 3 views
0

WPF UserControl을 가능한 한 일반화하기 위해 노력하고 있습니다. 모든 사용자 정의 컨트롤에서 가져올 수있는 기본 클래스를 정의했습니다. UserControl 또는 기본 클래스에 대한 형식 매개 변수를 지정하여 일반 만들 수 싶습니다하지만이 가능하지 않습니다. 작품으로 유형 변수에 유형이 저장되어있는 클래스의 인스턴스를 만드는 방법은 무엇입니까?

주위에 내가 예를 들어 매개 변수로 타입을 설정하려고 해요 :

public class UCBase : UserControl 
{ 
    public virtual Type UCType { get; private set; } 
    public virtual Type PanelType { get; private set; } 

    internal void SetType<TVM, TPanel>() where TPanel : new() 
    { 
     UCType = typeof(TVM); 
     PanelType = typeof(TPanel); 

    } 
} 

나중에, 나는 UCType가 나타내는 인스턴스를 클래스를 생성하는 방법을 알고 특별히 다른 사용자가 제어해야 ViewModel을 다루기 위해 저는 그것을 통과시킬 것입니다.

public ZonesAccordionPanel(List<ViewModelBase> vmItems) 
    { 
     InitializeComponent(); 

     foreach (var item in vmItems) 
     { 
      var exp = new Expander { Header = new ZoneReport(item) }; 
      exp.Resources.Add("item", item); 
      exp.Expanded += exp_Expanded; 

      accordion.Children.Add(exp); 
     } 

    } 


    void exp_Expanded(object sender, RoutedEventArgs e) 
    { 
     var expander = (Expander) sender; 
     var currentItem = expander.Resources["item"]; 

     // I have my data and I'd like to pass that to a specific UserControl 
     // that knows how to deal with that data the way I want 

    } 

어떻게 내가 SetType<TVM, TPanel>() 설정 유형 매개 변수를 기반으로 해당 사용자 제어를 할 수 있습니까?

유형을 public virtual Type PanelType { get; private set; }에 저장 한 클래스의 인스턴스를 만들 수 있습니까?

그렇다면 어떻게됩니까?

+0

Activator.CreateInstance를 보았습니까? 'UCType' 타입이 generic (다른 말로'UCType ')이라면,'Activator.CreateInstance (UCType.MakeGenericType (new [] {PanelType}), )'할 수 있습니다. – SPFiredrake

답변

관련 문제