绑定到ItemsPresenter属性
问题描述:
我有以下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项目主机的属性?
答
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"/>
为您的标签声明。
感谢您的解决方法......如果绑定目标不是模板项目,它确实有效。如果我想绑定到同一个ItemsControl ControlTemplate中的同级元素,会发生什么? – Mart 2011-01-07 17:31:46