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:
<DataGrid.RowHeaderStyle>
<Style TargetType="DataGridRowHeader">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Button Content="{Binding Path=PlusMinus}"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="Transparent"
Height="20"
Width="20"
Margin="0"
Padding="0"
Visibility="{Binding Path=IsManager, Converter={StaticResource bool2Visibility}}"
Click="CollapseAction">
</Button>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGrid.RowHeaderStyle>
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:
<Window.Resources>
<BooleanToVisibilityConverter x:Key="bool2Visibility"/>
</Window.Resources>
Now you can
use the bool2Visibiity key to bink on your button
Visibility Porperty:
Visibility="{Binding Path=IsManager, Converter={StaticResource bool2Visibility}}"
Click="CollapseAction"/>
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. |
See you soon!!
Um grande abraço e até
a próxima!
TapiocaCom
Team.
No comments:
Post a Comment