简体   繁体   中英

WPF: How to find control by code behind

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
}

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...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM