开发者

How can I choose different DataContext for UserControl based on property?

开发者 https://www.devze.com 2023-01-12 15:44 出处:网络
I want to choose different DataContext for UserControl, based on what user specified in xaml, suppose I have a user control:

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();
        }
    }

    ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号