Access control within datatemplate

送分小仙女□ 提交于 2019-12-23 18:49:37

问题


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


回答1:


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!




回答2:


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


来源:https://stackoverflow.com/questions/6229514/access-control-within-datatemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!