Dante
Dante

Reputation: 3316

How to Pass a Control to a Property in WPF?

I am working on a project on WPF and I have to create some user controls. Right now I am developing a navigation bar which allows me to navigate through a datagrid, so in my XAML file I need to pass the datagrid object to the navigation bar, but it is not working.

My navigation bar is the following:

<my:NavigationBar Data="{Binding ElementName=dataGrid1}" HorizontalAlignment="Left" Margin="6,6,0,0" Name="navigationBar1" VerticalAlignment="Top" />

And my data grid is the following:

<DataGrid AutoGenerateColumns="True" Margin="11,46,12,9" Name="dataGrid1" />

And my code behind my navigation bar is the following:

    public static readonly DependencyProperty dataProperty =
        DependencyProperty.Register("Data",
                                    typeof(DataGrid), typeof(NavigationBar));

    private DataGrid dataGrid;
    public DataGrid Data
    {
        get
        { return dataGrid; }
        set
        { dataGrid = value; }
    }

As you can see, I try to send the control to the navigation bar by doing this:

Data="{Binding ElementName=dataGrid1}"

But when I try to use the dataGrid variable in my code behind, an exception is raised because the dataGrid variable is pointing to null.

So, am I passing incorrectly the control? What am I doing wrong? Is my approach the most appropiate?

Thank you in advance.

Upvotes: 0

Views: 329

Answers (2)

Steven Magana-Zook
Steven Magana-Zook

Reputation: 2759

While i agree with Andriy that there may be a better way to handle this, i do see a problem in the way you are doing Dependency Properties.

Your backing properties for the DependencyProperty are not correct. You are not supposed to just get and set a regular value. Instead, you are supposed to use SetValue and GetValue methods.

Should be:

public DataGrid Data
    {
        get
        { return (DataGrid) GetValue(dataProperty); }
        set
        { SetValue(dataProperty); }
    }

See: http://www.wpftutorial.net/DependencyProperties.html

Upvotes: 0

Andriy Zakharko
Andriy Zakharko

Reputation: 1673

DataGrid is aimed to show data in a human-readable way - you shouldn't pass it as a DataSource into your control. Try to bind your navigation bar form the same datasource as datagrid1

Upvotes: 1

Related Questions