Binding to DataGridTemplateColumn
I have a User table and I have a foreign key of this table from a Book table. the FK is ProxyRe开发者_StackOverflow社区sponsibleUser_ID. when I use DataGridTextColumn in my DataGrid anything is OK but now I want to use DataGridTemplateColumn to display the FullName column from User table for corresponding user with ProxyResponsibleUser_ID. I get an error since DataGridTemplateColumn does not have a Binding property.
So, by which property of DataGridTemplateColumn will I bind the ProxyResponsibleUser_ID? Thanks in advance.
<DataGridTextColumn x:Name="securityConfigurationNameColumn" Binding="{Binding Path=SecurityConfigurationName}" Header="Security Configuration Name" Width="*" />
<DataGridTemplateColumn x:Name="proxyResponsibleUser_IDColumn" Binding="{Binding Path=ProxyResponsibleUser_ID}" Header="Proxy Responsible User ID" Width="*" >
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate DataType="{x:Type domain:User}">
<TextBlock Text="{Binding FullName}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
I have been struggling with this question for quite a while, and after many fruitless searches, I came up with an acceptable substitute.
To anyone else searching for this: Try creating a custom implementation of DataGridBoundColumn. You will only need to override two methods: GenerateElement and GenerateEditingElement.
Example:
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
Label element = new Label();
element.SetBinding(Label.ContentProperty, Binding);
return element;
}
Usage:
<DataGrid>
<DataGrid.Columns>
<DataGridCustomColumn Binding="{Binding SomeProperty}" />
<DataGridCustomColumn Binding="{Binding OtherProperty}" />
</DataGrid.Columns>
</DataGrid>
Though I originally intended to use templates, I have opted to create elements in the code-behind as my needs are rather simple; however, I see no reason why this could not be adapted to work with DataTemplates given the proper DependencyProperty registrations.
I don't see exactly what you want to do, but the Binding has to be done at the TextBlock exactly as you already did. Therefore the Binding in the DataGridTemplateColumn-Tag is needless. There is no need for the column to know the id of the record.
If you want to have the id available to the TextBox-control (commonly not needed because you have access to this property directly through the DataContext), you can do this for example by binding the Tag-property.
<TextBlock Text="{Binding FullName}" Tag="{Binding ProxyResponsibleUser_ID}"/>
By the way, you declared a TextBlock in the EditTemplate. Maybe you want a TextBox. Or do you want to allow the user to change the Id? Make a comment if this is the case.
Hope this helps.
精彩评论