Wednesday, May 8, 2013

How insert a button in a datagrid row header

Sometimes we need to do some strange things, like adding a button in a row header of a datagrid. In my case I am looking for something like a treeview datagrid, and adding a button in a datagrid row header is one of the things we need to do (here the part 1 of my saga, where we show how to collapse lines in a datagrid). So, in this post we are going to show some tricks to let you bind your View Model Property with your button properties.
My .xaml code that insert the button in the row header became like this:
<Style TargetType="DataGridRowHeader">
             <Setter Property="Template">
<Button Content="{Binding Path=PlusMinus}"
Visibility="{Binding Path=IsManager, Converter={StaticResource bool2Visibility}}"
To edit the template you need to indicate the Target Type of your Style to DataGridRowHeader:
<Style TargetType="DataGridRowHeader">
This let you set the Template Property in the next line:
<Setter Property="Template">
Now you can bind the button property to the property on your view model. For example, the Visibility property. In my case I want the buttons just appear when the employee is a Manager. Because the visibility can be of three types (I describe here what values the visibility class can take) I needed to use a Converter. Microsoft provide a basic Boolean to Visibility converter, when your Boolean is true it returns a Visible Visibility. When the Boolean is false it returns a Collapsed Visibility.
To declare this converter you need to add it to the Windows Resource and add a Key to it:
<BooleanToVisibilityConverter x:Key="bool2Visibility"/>

Now you can use the bool2Visibiity key to bink on your button Visibility Porperty:
Visibility="{Binding Path=IsManager, Converter={StaticResource bool2Visibility}}"

You can download the source code of a primitive treeview datagrid that contains the code I described here in the link above.

Link to download

The figure below shows the final result.

Button in the datagrid row header.
 If this post was helpful or you have some doubt let us a comment!!

See you soon!!
Um grande abraço e até a próxima!
TapiocaCom Team.

No comments:

Post a Comment