Reputation: 885
I need to find datagrid control, which is situated near combobox, by a code behind. Sender is a ComboBox
.
XAML code:
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVis" />
<Style TargetType="{x:Type ComboBox}" x:Key="ComboboxSpreadsheetStyle">
<Setter Property="SelectedIndex" Value="0"/>
<EventSetter Event="SelectionChanged" Handler="Combobox_SelectionChanged"/>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<ComboBox Grid.Row="0" Style="{StaticResource ComboboxSpreadsheetStyle}">
<ComboBoxItem x:Name="it1">Item1</ComboBoxItem>
<ComboBoxItem x:Name="it2">Item2</ComboBoxItem>
</ComboBox>
<DataGrid Background="Blue" Grid.Row="1" Visibility="{Binding ElementName=it1, Path=IsSelected, Converter={StaticResource BoolToVis}}">
<DataGrid.Columns>
<DataGridTextColumn>
<DataGridTextColumn.Header >
<TextBlock Text="Text1"/>
</DataGridTextColumn.Header>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
<DataGrid Background="Red" Grid.Row="1" Visibility="{Binding ElementName=it2, Path=IsSelected, Converter={StaticResource BoolToVis}}">
<DataGrid.Columns>
<DataGridTextColumn>
<DataGridTextColumn.Header >
<TextBlock Text="Text2"/>
</DataGridTextColumn.Header>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
CS code:
private void Combobox_SelectionChanged(object sender, RoutedEventArgs e)
{
//find dataGrid control
}
Upvotes: 3
Views: 4139
Reputation: 13679
You may perhaps specify a name to your DataGrid and access the same via name in the code behind
here is an example
<DataGrid Background="Blue" Grid.Row="1" Visibility="{Binding ElementName=it1, Path=IsSelected, Converter={StaticResource BoolToVis}}"
x:Name="myGrid">
<DataGrid.Columns>
....
now you can access the DataGrid in codebehind as myGrid
eg
private void Combobox_SelectionChanged(object sender, RoutedEventArgs e)
{
//find dataGrid control
//myGrid.FillData etc...
}
Upvotes: 11