3

This is 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>

This is codebehind:

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);
}

Is there a more simple way to access the textbox? (As I know I can't get Parent of parent e.g. Parent.Parent...)

H.B.
  • 166,899
  • 29
  • 327
  • 400
anderi
  • 767
  • 2
  • 11
  • 18

2 Answers2

2

Your code is not that complex!

However, you could simplify it by using 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);
}

The Linq query above finds the first DockPanel ancestor of your RadioButton (i.e. the Parent.Parent that you wanted!), then finds the first TextBox child of the DockPanel.

However, I typically use Linq-to-VisualTree in cases where the query is more complex. I thin your approach is OK really!

H.B.
  • 166,899
  • 29
  • 327
  • 400
ColinE
  • 68,894
  • 15
  • 164
  • 232
0

Among other things you can add a reference to it in the 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;
    //...
}
H.B.
  • 166,899
  • 29
  • 327
  • 400