2011-01-06 111 views
0

我有以下XAML:綁定到ItemsPresenter屬性

<ItemsControl ItemsSource="{Binding...}" > 
    <ItemsControl.Template> 
     <ControlTemplate> 
      <ItemsPresenter x:Name="testGrid"/> 
     </ControlTemplate> 
    </ItemsControl.Template> 
    <!--Use the ItemsPanel property to specify a custom UniformGrid that 
    holds the laid out items.--> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
      <tools:UniformGridRtL Columns="8" x:Name="testGrid2" /> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 

    <!--Use the ItemTemplate to set a DataTemplate to define 
     the visualization of the data objects. This DataTemplate 
     specifies that each data object appears RegisterBit appears 
     as a CheckBox bound to RegisterBit properties. It also defines 
     a custom template for the checkbox.--> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <CheckBox... /> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

<Label> 
    <Binding ElementName="testGrid2" Path="property_of_UniformGridRtL"/> 
</Label> 

基本上,我有設定爲ItemsPanelTemplate定製面板(UniformGridRtL),這將在ItemsControl的模板的ItemsPresenter。 UniformGridRtL有一個我想綁定的屬性,但ElementName在標籤綁定中似乎不起作用。 如何綁定到生成的ItemsControl項目主機的屬性?

回答

0

ElementName綁定源不適用於模板項目,即使是通常只有單個模板項目的ItemsPanelTemplate項目。問題是,因爲它是一個模板,理論上可以有多個模板,所以WPF不知道要綁定哪個命名項。

作爲一個變通辦法,嘗試訂閱所述面板的Loaded事件(在該情況下<tools:UniformGridRtL Loaded="grid_Loaded" .../>),然後設置手動裝訂在代碼:

private void grid_Loaded(object sender, RoutedEventArgs e) 
{ 
    Binding binding = new Binding("NameOfGridPropertyToBindTo"); 
    binding.Source = sender; 
    boundLabel.SetBinding(Label.ContentProperty, binding); 
} 

上面的代碼假定類似<Label Name="boundLabel"/>爲您的標籤聲明。

+0

感謝您的解決方法......如果綁定目標不是模板項目,它確實有效。如果我想綁定到同一個ItemsControl ControlTemplate中的同級元素,會發生什麼? – Mart 2011-01-07 17:31:46