我有以下XAML:
<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>基本上,我有一个自定义面板(UniformGridRtL)设置为ItemsPanelTemplate,它将模板的ItemsPresenter中的ItemsControl。UniformGridRtL有一个我想绑定的属性,但是ElementName在标签绑定中似乎不起作用。如何绑定到生成的ItemsControl项宿主的属性?
发布于 2011-01-07 02:48:23
ElementName绑定源不适用于模板化的项,即使是通常只有一个模板化的项的ItemsPanelTemplate项。问题是,因为它是一个模板,理论上您可以有多个模板,所以WPF不知道要绑定到哪个命名项。
作为一种解决办法,可以尝试订阅面板的已加载事件(在本例中为<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"/>。
https://stackoverflow.com/questions/4618275
复制相似问题