Binding an attached property to an item in ItemsControl with custom panel problem

本秂侑毒 提交于 2020-01-02 06:23:10

问题


I can't get the following XAML to work as I want. All bindings work because get no errors from the bindings. But I don't get the expected result from the binding on the RatioShape rectangle. The problem is that the attached property wpflib:RatioPanel.Ratio always returns its default value, not the databound value.

So I'm thinking that the attached property on RatioShape is set in the wrong "context". How do bind to the attached property so that wpflib:RatioPanel gets the bound value?

<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:


The children of the RatioPanel will be instances of ContentPresenter, assuming the items are not UIElements. The ContentPresenter will display the DataTemplate you have defined in ItemTemplate.

Normally, panels work directly with their children. You are setting your attached property on the a child of the ContentPresenter, which is a child of your panel. I believe you should be setting this on the ContentPresenter directly. So something like this:

<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>


来源:https://stackoverflow.com/questions/6126183/binding-an-attached-property-to-an-item-in-itemscontrol-with-custom-panel-proble

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!