首页 > 解决方案 > WPF 将子控件的 ActualWidth 和 ActualHeight 传递给值转换器

问题描述

使用 WPF,我希望为集合中的每个数据集创建一个图像并显示垂直堆叠的图像。所有图像必须具有相同的高度(和宽度)。堆叠在一起的图像必须构成包含元素的高度。不得以任何方式拉伸图像。

我所追求的那种东西的一个不工作的假装例子如下。

<UniformGrid Columns="1" DataContext="{Binding DataSetCollection}">
    <UniformGrid.Children>
        <MultiBinding Converter="{StaticResource DataSetToImageConverter}">
            <Binding />
            <Binding Path="ActualWidth" RelativeSource="{RelativeSource AncestorType={x:Type UniformGridRow}}" />
            <Binding Path="ActualHeight" RelativeSource="{RelativeSource AncestorType={x:Type UniformGridRow}}" />
        </MultiBinding>
    </UniformGrid.Children>
</UniformGrid>

由于多种原因,这不起作用,但希望能传达意图。关键要求是:

它不必使用 UniformGrid,它可以是任何东西,但是它应该为每个孩子使用数据绑定和转换器。

标签: wpfdata-binding

解决方案


这成功了,绑定到包含 ContentPresenter 的大小。

<ItemsControl ItemsSource="{Binding DataSetCollection}" ItemTemplate="{StaticResource WriteableBitmapDataTemplate}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="1" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

使用此数据模板

<DataTemplate x:Key="WriteableBitmapDataTemplate">
    <Image>
        <Image.Source>
            <MultiBinding Converter="{StaticResource RangeToWritableBitmapConverter}">
                <Binding />
                <Binding Path="ActualWidth" RelativeSource="{RelativeSource AncestorType={x:Type ContentPresenter}}" />
                <Binding Path="ActualHeight" RelativeSource="{RelativeSource AncestorType={x:Type ContentPresenter}}" />
            </MultiBinding>
        </Image.Source>
    </Image>
</DataTemplate>

推荐阅读