How can I choose different DataContext for UserControl based on property?
I want to choose different DataContext for UserControl, based on what user specified in xaml, suppose I have a user control:
public partial class UcMyControl : UserControl
{
开发者_如何学Python public UcMyControl()
{
InitializeComponent();
if (Group == "Group1")
this.DataContext = DataContextA;
else if (Group == "Group2")
this.DataContext = DataContextB;
else
this.DataContext = ...;
}
public string Group { set; get; }
...
}
And In XAML:
<uc:UcMyControl Group="GroupA" />
But the problem is, Group is always null in ctor, so it won't work... What I need is to exam a user specified value (Group in this case) before I set DataContext for UcMyControl. Is there some way to work around it?
Implement a property with implementation and refresh the datacontext when the group is set
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();
}
}
...
}
精彩评论