2010-08-24 56 views
2

我想選擇的用戶控件不同的DataContext的基礎上,在XAML指定哪些用戶,假設我有一個用戶控件:如何根據屬性爲UserControl選擇不同的DataContext?

public partial class UcMyControl : UserControl 
{ 
    public UcMyControl() 
    { 
     InitializeComponent(); 

     if (Group == "Group1") 
      this.DataContext = DataContextA; 
     else if (Group == "Group2") 
      this.DataContext = DataContextB; 
     else 
      this.DataContext = ...; 
    } 

    public string Group { set; get; } 

    ... 
} 

並在XAML:

<uc:UcMyControl Group="GroupA" /> 

但問題是,集團在ctor中總是爲空,所以它不會工作...我需要的是在爲UcMyControl設置DataContext之前檢查用戶指定的值(在這種情況下爲Group)。有什麼辦法可以解決它嗎?

回答

1

與執行實施的屬性和刷新的datacontext當組設置

public partial class UcMyControl : UserControl 
{ 
    public UcMyControl() 
    { 
     InitializeComponent(); 

    } 

    public void SetDataContext() 
    { 
     if (Group == "Group1") 
      this.DataContext = DataContextA; 
     else if (Group == "Group2") 
      this.DataContext = DataContextB; 
     else 
      this.DataContext = ...; 
    } 

    private string _group; 
    public string Group 
    { 
     get 
     { 
      return _group; 
     } 
     set 
     { 
      _group = value; 
      SetDataContext(); 
     } 
    } 

    ... 
} 
+0

作品非常好,好招! – neolei 2010-08-24 12:54:48