简体   繁体   中英

accessing control item when given inner template element

I have a TreeviewItem with a style set to this

    <Style x:Key="TreeViewItemStyle" TargetType="TreeViewItem">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="TreeViewItem">
                        <StackPanel x:Name="stackpanel" Orientation="Horizontal">
                            <CheckBox x:Name="checkbox_treeview" Checked="treeView_AfterCheck" Unchecked="treeView_AfterCheck"/>
                            <Image x:Name="image_treeview" Width="16"/>
                            <local:WPFEditableTextBlock x:Name="label_TreeView" Text="{TemplateBinding Header}"/>
                        </StackPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

I am able to access the checkbox of the template by doing this

TreeViewItem folderNode = new TreeViewItem();
Style style = this.FindResource("TreeViewItemStyle") as Style;
folderNode.Style = style;
ControlTemplate controlTemplate = folderNode.Template;
var templatedControl = folderNode.Template.LoadContent() as FrameworkElement;
CheckBox chbx = (CheckBox)templatedControl.FindName("checkbox_treeview");

once I am able to access this checkbox I have it go to the checked event handler. within that I want to be able to access the treeViewItem that contains that checkbox , but I can't figure out how to do this. Please help me out!!!

To access the treeViewItem from the checkbox defined in the template you could pass it in the Tag property from xaml like so:

 <ControlTemplate TargetType="TreeViewItem">
                    <StackPanel x:Name="stackpanel" Orientation="Horizontal">
                        <CheckBox x:Name="checkbox_treeview" Tag="{Binding RelativeSource={RelativeSource AncestorType={x:Type TreeViewItem}}}" Checked="treeView_AfterCheck" Unchecked="treeView_AfterCheck"/>
                        <Image x:Name="image_treeview" Width="16"/>
                        <local:WPFEditableTextBlock x:Name="label_TreeView" Text="{TemplateBinding Header}"/>
                    </StackPanel>
 </ControlTemplate>

and here how to retrieve it from the event handler:

private void treeView_AfterCheck(object sender, RoutedEventArgs e)
{
     var tvi = ((sender as CheckBox).Tag as TreeViewItem);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM