我需要通过后面的代码找到位于组合框附近的数据网格控件。发件人是ComboBox
。
XAML代码:
<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代码:
private void Combobox_SelectionChanged(object sender, RoutedEventArgs e)
{
//find dataGrid control
}
答案 0 :(得分:10)
您可以为DataGrid指定一个名称,并在
后面的代码中访问相同的名称这是一个例子
<DataGrid Background="Blue" Grid.Row="1" Visibility="{Binding ElementName=it1, Path=IsSelected, Converter={StaticResource BoolToVis}}"
x:Name="myGrid">
<DataGrid.Columns>
....
现在您可以将代码隐藏中的DataGrid作为myGrid
例如
private void Combobox_SelectionChanged(object sender, RoutedEventArgs e)
{
//find dataGrid control
//myGrid.FillData etc...
}