2014-12-03 37 views
0

美好的一天。我怎麼能從ControlBox的ListBoxItem控件?

對於列表框的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來完成。但我不知道如何使用這種方法。

如何從ControlTemplate中提取網格?

+0

控件位於項目模板中,因此您可能需要在列表框項而不是列表框中調用此方法。有關示例,請參閱[FrameworkTemplate.FindName](http://msdn.microsoft.com/zh-cn/library/system.windows.frameworktemplate.findname%28v=vs.110%29.aspx)。 – pushpraj 2014-12-03 12:05:27

+2

您不需要。無論你想要做什麼,都要使用適當的DataBinding。程序性地操縱模板中的UI元素是有史以來最糟糕的想法,除非你有一個好的理由,我認爲你沒有。 – 2014-12-03 12:09:39

+0

您應該使用觸發器或模板選擇器,而不是通過代碼操縱控件 – Bijan 2014-12-03 13:25:23

回答

0

您試圖從ListBoxItem的模板中獲取元素,而不是從ListBox中獲取元素。因此,在使用訪問模板之前,您需要獲取確切的ListBoxItem。在下面的代碼片段中,我向您展示瞭如何從第0個元素獲取項目並從其模板中獲取Grid。

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