njebert
njebert

Reputation: 544

Access bound object in UserControl code behind with DependencyProperty

I am having trouble setting a property of a custom user control using a DependencyProperty through databinding on the parent UserControl.

Here is the code for my custom UserControl:

public partial class UserEntityControl : UserControl
{
    public static readonly DependencyProperty EntityProperty =  DependencyProperty.Register("Entity",
        typeof(Entity), typeof(UserEntityControl));

    public Entity Entity
    {
        get
        {
            return (Entity)GetValue(EntityProperty);
        }
        set
        {
            SetValue(EntityProperty, value);
        }
    }

    public UserEntityControl()
    {
        InitializeComponent();
        PopulateWithEntities(this.Entity);
    }
}

I want access to the Entity property in the code behind because that will dynamically build the user control based on values stored in the Entity. The problem that I am having is that the Entity property is never set.

Here is how I am setting up the binding in the parent user control:

<ListBox Grid.Row="1" Grid.ColumnSpan="2" ItemsSource="{Binding SearchResults}"     x:Name="SearchResults_List">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <!--<views:SearchResult></views:SearchResult>-->
            <eb:UserEntityControl  Entity="{Binding}" ></eb:UserEntityControl>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

I am setting the ItemsSource of the ListBox to SearchResults, which is an Observable Collection of Entities (The same type as Entity on the custom UserControl).

I am not getting any runtime binding errors in the debug output window. I just cannot set the value of the Entity property. Any ideas?

Upvotes: 2

Views: 1072

Answers (1)

Elad Katz
Elad Katz

Reputation: 7591

You are trying to use the Entity property in the c-tor, which is too soon. the c-tor is going to be fired BEFORE the property value is going to be given.

What u need to do is to add a propertyChanged Event HAndler to the DependencyProperty, like so:

    public static readonly DependencyProperty EntityProperty = DependencyProperty.Register("Entity",
typeof(Entity), typeof(UserEntityControl), new PropertyMetadata(null, EntityPropertyChanged));

    static void EntityPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var myCustomControl = d as UserEntityControl;

        var entity = myCustomControl.Entity; // etc...
    }

    public Entity Entity
    {
        get
        {
            return (Entity)GetValue(EntityProperty);
        }
        set
        {
            SetValue(EntityProperty, value);
        }
    }

Upvotes: 3

Related Questions