将附加属性绑定到ItemsControl中带有自定义面板的项目存在问题

5
我无法让以下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>
1个回答

8

假设项目不是UI元素,RatioPanel的子项将是ContentPresenter的实例。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>

1
为什么附加属性必须以不同的方式设置?这太令人困惑了。该死的WPF。 - Konrad
12年后,仍然是一个有用的答案。ChatGPT无法超越一些经典的回答。 - IneedHelp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接