Привязка к свойству ItemsPresenter - PullRequest
0 голосов
/ 06 января 2011

У меня есть следующий 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 items?

1 Ответ

0 голосов
/ 06 января 2011

Источник привязки 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"/> для вашего объявления Label.

...