views:

18

answers:

1

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
{
    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?

+1  A: 

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

    ...
}
Wouter Janssens - Xelos bvba
Works very good, nice trick!
sun1991