这是XAML:
<Window.Resources>
<DataTemplate x:Key="Temp">
<DockPanel Width="Auto" Background="White" LastChildFill="False">
<TextBox Name="txtBox" TextWrapping="Wrap" DockPanel.Dock="Left" Text="{Binding RelativeSource={RelativeSource AncestorType=ContentControl}, Path=Content}" Height="20" Width="100"/>
<StackPanel Orientation="Vertical">
<RadioButton Content="Option1" HorizontalAlignment="Left" Height="16" Width="112" Click="RadioButton_Click" />
</StackPanel>
</DockPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ContentControl ContentTemplate="{DynamicResource Temp}" Content="1"/>
</Grid>
这是代码隐藏:
private void RadioButton_Click(object sender, RoutedEventArgs e)
{
StackPanel sp = ((RadioButton)sender).Parent as StackPanel;
DockPanel dp = sp.Parent as DockPanel;
TextBox txtbox = dp.FindName("txtBox") as TextBox;
MessageBox.Show(txtbox.Text);
}
是否有更简单的方法来访问文本框? (据我所知,我不能得到父母的父母,例如Parent.Parent ......)
答案 0 :(得分:2)
你的代码并不复杂!
但是,您可以使用Linq-to-VisualTree:
来简化它private void RadioButton_Click(object sender, RoutedEventArgs e)
{
RadioButton rb = sender as RadioButton;
TextBox txtbox= rb.Ancestors<DockPanel>().First().Elements<TextBox>().First() as TextBox;
MessageBox.Show(txtbox.Text);
}
上面的Linq查询找到了DockPanel
的第一个RadioButton
祖先(即您想要的Parent.Parent
!),然后找到了TextBox
的第一个DockPanel
个孩子。 {1}}。
但是,在查询更复杂的情况下,我通常使用Linq-to-VisualTree。我瘦你的方法真的很好!
答案 1 :(得分:0)
除此之外,您还可以在RadioButton.Tag中添加对它的引用:
<RadioButton Content="Option1" HorizontalAlignment="Left" Height="16" Width="112"
Click="RadioButton_Click" Tag="{x:Reference txtBox}" />
private void RadioButton_Click(object sender, RoutedEventArgs e)
{
var textBox = (sender as FrameworkElement).Tag as TextBox;
//...
}