Search code examples
wpfbindinguser-controlscode-behindcustom-object

Accessing bound context in user controls code behind


Question is much like this question- just didn't pan out for me

So how do I access a Property on a WPF usercontrol bound via Parent's Xaml in, from the Controls Code behind?

PS: Other controls bound to Properties of the TowerBase model passed in are binding. ( I just can't access the model passed in in the code behind ).

UserControl: x and y are null and I can't figure out why

public partial class TowerControl : UserControl
{
    public TowerBase model = new TowerBase(); //Trying to set this model

    public TowerControl()
    {
        InitializeComponent();
        var x = ((TowerBase)this.DataContext); //Or Extract from binding
        var y = model;
    }
    ...

From the parent's xaml:

    ...
    <controls:TowerControl Grid.Row="1" Grid.Column="0" x:Name="Tower" DataContext="{Binding Tower}" />
    ...

Parent Model:

    ...
    public TowerBase Tower { get; set; }
    ...

Solution

  • That is because UserControl's DataContext would not be set by the time it is in constructor. Listen to Loaded event of user control and in handler you will get the DataContext

    <UserControl Loaded="UserControl_Loaded">
    
    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
        var x = this.DataContext;
    }