Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: How to find control by code behind

Tags:

c#

wpf

xaml

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
}
like image 266
Artem Kyba Avatar asked Mar 04 '26 16:03

Artem Kyba


1 Answers

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...
}
like image 94
pushpraj Avatar answered Mar 06 '26 05:03

pushpraj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!