In my MainView, I have a button: In my MainView, I have a button: In my MainView, I have a button:

How to find an element by name in other user control?

525 Views Asked by At

I have a user control (MainView) with an other user control (GridView):

<local:MyGridView x:Name="GridView"/>

In my MainView, I have a button:

<Button Command="{Binding TestCommand}"  
        CommandParameter="{Binding ElementName=DataGrid}" 
        Content="Test"/>

In my GridView, I have a data grid that I want to send as a CommanParameter. If the GridView code was in the MainView code, this syntax would work. What should I change?

I tried {Binding ElementName=GridView.DataGrid} - no success.

2

There are 2 best solutions below

1
Taehyung Kim On BEST ANSWER

Very simple.

<local:MyGridView x:Name="**GridView**"/>

<Button Command="{Binding TestCommand}"  
        CommandParameter="{Binding ElementName=**GridView**}" 
        Content="Test"/>

You should change the ElementName from DataGrid To GridView.

1
mm8 On

You cannot use ElementName to directly reference an element that is defined in another control or namescope.

What you could do is to add a property to MyGridView.xaml.cs that exposes the DataGrid control:

public DataGrid DataGrid => dataGrid1;

You could then bind to this property of the element:

<Button Command="{Binding TestCommand}"  
        CommandParameter="{Binding Path=DataGrid, ElementName=GridView}" 
        Content="Test"/>

A better approach would be use a shared DataContext (view model) and bind both controls to properties of this one.