使用需要参数的转换器的可重用 DataTemplate(在参考资料中)

Reusable DataTemplate (in Resources) using a convertor that needs a parameter

我必须在网格中显示 12 列(每个月一列)的不同数据。 为了正确显示数据,我为每一列和多重绑定使用 DataTemplates。多重绑定指定一个转换器,该转换器使用月份索引进行参数化。

 <DataTemplate x:Key="CustomerForecastQuantityDataTemplate">
    <TextBlock TextAlignment="Right">
        <TextBlock.Text>
            <MultiBinding Converter="{StaticResource ForecastCustomerQuantityConverter}" **ConverterParameter="0"**>
                            <Binding RelativeSource="{RelativeSource AncestorType={x:Type view:BaseView}}" Path="DataContext.ForecastPeriods"/>
                            <Binding Path="ForecastQuantities"/>
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>
</DataTemplate>

我正在尝试让 xaml 看起来更优雅一些,并将一个 DataTemplate 定义为静态资源,并在任何地方使用它,如下所示:

<forecast:ForecastCustomerMonthQuantityGridViewDataColumn
    Header="{Binding RelativeSource={RelativeSource Self}, Path=MonthIndex}"
    HeaderTextAlignment="Center"
    HeaderTextWrapping="Wrap"
    Width="60"
    IsReadOnly="True"
    MonthIndex="1"
    CellTemplate="{StaticResource CustomerForecastQuantityDataTemplate}"/>

我的问题是,如何让这个 DataTemplate 根据每个 ForecastCustomerMonthQuantityGridViewDataColumn 的 MonthIndex 值采用不同的参数

非常感谢,非常感谢每一个建议(可能是我对DataTemplate的概念没有很好的理解)

我想不出从单元格模板中获取 "MonthIndex" 的 XAML 唯一方法(附带说明 ConverterParamter 不支持绑定) .在我的脑海中,你可以尝试这样的事情(我不在我的电脑旁所以不能自己尝试):-

向您的多值转换器添加第三个绑定,绑定到正在模板化的单元格,例如:

<binding RelativeSource="{RelativeSource AncestorType={x:Type DataGridCell}}" />

您的多值转换器现在可以访问该单元格,该单元格又​​公开了一个 Column 属性,您可以将其转换为 ForecastCustomerMonthQuantityGridViewDataColumn 以获取 "MonthIndex" .