簡體   English   中英

我如何從ListBoxItem的ControlTemplate獲得控制權?

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

美好的一天。

對於ListBox的ItemContainerStyle,我設置了自己的樣式:

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

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

在代碼中,我想檢索所選項目的網格控件。 我試圖通過listBoxGallery.Template.FindName做到這listBoxGallery.Template.FindName 但是我不知道如何使用這種方法。

如何從ControlTemplate提取網格?

您正在嘗試從ListBoxItem的模板而不是ListBox獲取元素。 因此,在使用其模板之前,您需要獲取准確的ListBoxItem。 在下面的代碼片段中,我向您展示了如何從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