简体   繁体   English

我如何从ListBoxItem的ControlTemplate获得控制权?

[英]How could i get control from ControlTemplate of ListBoxItem?

Good day. 美好的一天。

For ItemContainerStyle of ListBox I set my own style: 对于ListBox的ItemContainerStyle,我设置了自己的样式:

StyleClass.xaml StyleClass.xaml

<Style x:Key="ItemContainerGalleryStyle" TargetType="{x:Type ListBoxItem}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBoxItem}">
                <Grid x:Name="itemGrid">
                    ...
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style x:Key="ListBoxGalleryStyle2" TargetType="{x:Type ListBox}">
    <Setter Property="ItemContainerStyle" Value="{DynamicResource ItemContainerGalleryStyle}" />
</Style>

MainWindow.xaml MainWindow.xaml

<Window ...>
<Window.Resources>
    <XmlDataProvider x:Key="GalleryXmlDataProvider"  Source="Gallery.xml"></XmlDataProvider>
</Window.Resources>
<Grid>        
    <ListBox x:Name="listBoxGallery" 
             Style="{StaticResource ListBoxGalleryStyle2}"                 
             ItemsSource="{Binding Mode=Default, 
                            Source={StaticResource GalleryXmlDataProvider}, 
                            XPath=/Gallery/Image}" />
    </Grid>
</Window>

In code I want to retrieve Grid Control of my selected item. 在代码中,我想检索所选项目的网格控件。 I attempt to do it by means of a listBoxGallery.Template.FindName . 我试图通过listBoxGallery.Template.FindName做到这listBoxGallery.Template.FindName But I can't get at how to use this method. 但是我不知道如何使用这种方法。

How can I extract Grid from ControlTemplate? 如何从ControlTemplate提取网格?

You are trying to get an element from ListBoxItem's template and not from ListBox. 您正在尝试从ListBoxItem的模板而不是ListBox获取元素。 So you need to get the exact ListBoxItem, before you using accessing its template. 因此,在使用其模板之前,您需要获取准确的ListBoxItem。 In below code snippet, I shown you how to get item from 0th element and taking the Grid from its template. 在下面的代码片段中,我向您展示了如何从0th元素获取项目以及如何从其模板获取Grid。

var container = listBoxGallery.ItemContainerGenerator.ContainerFromIndex(0) as ListBoxItem;
var iremgrid = container.Template.FindName("itemGrid") as Grid;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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