Search code examples
c#wpfxamltelerikdatatemplate

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


I have to display in a grid 12 columns (one for each months) with different data. In order to correctly display the data, I use DataTemplates for every column and multibindings. The multibindings specify a converter which is parametrized with the index of the month.

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

I am trying to make the xaml look a bit more elegant, and have one DataTemplate defined as a static resource, and use it everywhere, like this:

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

My question is, how can I make this DataTemplate take a diferrent parameter depending on the MonthIndex value of each ForecastCustomerMonthQuantityGridViewDataColumn

Thanks a lot, every suggestion is highly appreciated (it might be that I don't have a good understanding of the DataTemplate concept)


Solution

  • I can't think of a XAML-only way to get at "MonthIndex" from within the cell template (and on a side note ConverterParamter doesn't support binding). Off the top of my head, you could try something like this (I'm away from my PC so not able to try it myself):-

    Add a third binding to your multi value converter, bound to the cell being templated, something like:

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

    Your multi value converter now has access to the cell, which in turn exposes a Column property, which you can cast to ForecastCustomerMonthQuantityGridViewDataColumn to get at "MonthIndex".