使用自定义面板问题将附加属性绑定到ItemsControl中的项目

Ste*_*hlm 4 wpf xaml binding attached-properties

我不能让以下XAML按我的意愿工作.所有绑定都起作用,因为绑定没有错误.但是我没有从RatioShape矩形的绑定中获得预期的结果.问题是附加属性wpflib:RatioPanel.Ratio始终返回其默认值,而不是数据绑定值.

所以我认为RatioShape上的附加属性设置在错误的"上下文"中.如何绑定到附加属性,以便wpflib:RatioPanel获取绑定值?

<wpflib:RatioContentPresenter2 RatioMaxValue="{Binding Path=RatioMaxValue}">
    <ItemsControl Grid.Row="0" wpflib:RatioContentPresenter2.RatioOffset="{Binding Path=RatioOffset}" wpflib:RatioContentPresenter2.RatioValue="{Binding Path=RatioValue}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                    <wpflib:RatioPanel />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>

        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Rectangle x:Name="RatioShape" wpflib:RatioPanel.Ratio="{Binding Path=Value}" Fill="{Binding Path=Brush}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>

        <ItemsControl.ItemsSource>
            <Binding  Path="RatioItems" Mode="OneWay" />
        </ItemsControl.ItemsSource>
    </ItemsControl>
</wpflib:RatioContentPresenter2>
Run Code Online (Sandbox Code Playgroud)

Cod*_*ked 6

RatioPanel的子节点将是ContentPresenter的实例,假设项目不是UIElements.ContentPresenter将显示您在ItemTemplate中定义的DataTemplate.

通常,面板直接与孩子一起工作.您正在ContentPresenter的子项上设置附加属性,该子项是您的面板的子项.我相信你应该直接在ContentPresenter上设置它.所以像这样:

<ItemsControl.ItemContainerStyle>
    <Style>
        <Setter Property="wpflib:RatioPanel.Ratio" Value="{Binding Path=Value}" />
    </Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Rectangle x:Name="RatioShape" Fill="{Binding Path=Brush}" />
    </DataTemplate>
</ItemsControl.ItemTemplate>
Run Code Online (Sandbox Code Playgroud)