0

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.

4

2 回答 2

1

DataGrid 旨在以人类可读的方式显示数据 - 您不应将其作为 DataSource 传递到您的控件中。尝试将导航栏绑定到与 datagrid1 相同的数据源

于 2012-05-21T18:17:20.093 回答
0

虽然我同意 Andriy 的观点,即可能有更好的方法来处理这个问题,但我确实看到您在执行依赖属性的方式中存在问题。

DependencyProperty 的支持属性不正确。你不应该只是获取和设置一个常规值。相反,您应该使用 SetValue 和 GetValue 方法。

应该:

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

请参阅: http: //www.wpftutorial.net/DependencyProperties.html

于 2012-05-21T18:24:03.303 回答