I am compiling some common CellTemplate styles for a WPF grid (WPFToolKit DataGrid), and Im not sure about the syntax used to create a generic binding type. So, for example, I have this template that turns the value into red if the value is negative:
<DataTemplate x:Key="RedNegativeCellTemplate"> <TextBlock Name="QuantityTextBox" Text="{Binding Quantity, StringFormat='c', Mode=OneWay}"/> <DataTemplate.Triggers> <DataTrigger Binding="{Binding Quantity, Converter={StaticResource SignConverter}}" Value="-1"> <Setter TargetName="QuantityTextBox" Property="Foreground" Value="Red"/> </DataTrigger> </DataTemplate.Triggers> </DataTemplate>
You will notice that this has a binding in the βTextβ field to the value of the βQuantityβ column - that is, the field / column from which the binding is derived is explicit.
Therefore, I can use this in my WPF DataGrid as follows:
<sdk:DataGrid ItemsSource="{Binding MyDataSource}" AutoGenerateColumns="False"> <sdk:DataGrid.Columns> <sdk:DataGridTemplateColumn Header="Net Quantity" CellTemplate="{StaticResource RedNegativeCellTemplate}"/> </sdk:DataGrid.Columns> </sdk:DataGrid>
But ... what the ID really likes is the binding of the field to the template, so I can reuse the template as follows:
<sdk:DataGrid ItemsSource="{Binding OrdersQuery}"AutoGenerateColumns="False"> <sdk:DataGrid.Columns> <sdk:DataGridTemplateColumn Header="Quantity" CellTemplate="{StaticResource RedNegativeCellTemplate}"/> <sdk:DataGridTemplateColumn Header="Price" CellTemplate="{StaticResource RedNegativeCellTemplate}"/> <sdk:DataGridTemplateColumn Header="Total" CellTemplate="{StaticResource RedNegativeCellTemplate}"/> </sdk:DataGrid.Columns> </sdk:DataGrid>
Now the problem is that there seems to be no way to parameterize the binding in CellTemplate. But I donβt want to have 3+ rows of a check table for each column that uses this template, as it clutters up the XAML and makes it much less readable (not to mention that if I decide to change the cell template to put a border around the text fields, I would have to change it in several places.
So, I think that the binding in CellTemplate should look something like this (note that we use "." For the binding path):
Text="{Binding Path=., StringFormat='c', Mode=OneWay}"
And then somehow set the datacontext from the DataGridTemplateColumn declaration, but I don't see how to do it.
Any ideas how to do this?