Access control within datatemplate
Asked Answered
N

2

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

Ninnyhammer answered 3/6, 2011 at 15:53 Comment(0)
A
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!

Ahearn answered 3/6, 2011 at 16:13 Comment(0)
H
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;
    //...
}
Hus answered 3/6, 2011 at 16:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.