Search code examples
c#wpfxamlcontroltemplate

Material Design (WPF): Remove CheckBox Background


I'm trying to display the square and the check mark only when the CheckBox is checked.

My code is as follows:

<CheckBox Content="Teste">
     <CheckBox.Resources>
           <SolidColorBrush x:Key="MaterialDesignCheckBoxOff" Color="White"/>
           <SolidColorBrush x:Key="PrimaryHueMidBrush" Color="Transparent"/>
     </CheckBox.Resources>
</CheckBox>

But, it doesn't work, when removing the background the enable mark disappears.

Image of how I want to leave my CheckBox:

Image of how the CheckBox should look


Solution

  • It looks like an easy thing to do, but it is not. The default template of the CheckBox in MaterialDesign uses a Path to draw the box and the check mark. In fact, it reuses the same Path, but only changes its Data property.

    • The Path is defined with its normal state (just the empty box)

      <Path x:Name="Graphic"
            Data="M19,3H5C3.89,3 3,3.89 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5C21,3.89 20.1,3 19,3M19,5V19H5V5H19Z" 
            Fill="{DynamicResource MaterialDesignCheckBoxOff}" />
      

      Example of the empty check box

    • The checked trigger for example changes the Data property to display a filled box. What you see is actually the filled box being drawn and the check mark in it is just not filled at all, it is a gap.

      <Trigger Property="IsChecked" Value="true">
         <Setter Property="Data" TargetName="Graphic" Value="M10,17L5,12L6.41,10.58L10,14.17L17.59,6.58L19,8M19,3H5C3.89,3 3,3.89 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5C21,3.89 20.1,3 19,3Z" />
         <Setter Property="Fill" TargetName="Graphic" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Background}" />
      </Trigger>
      

      Example of checked check box

    As you can see, changing the MaterialDesignCheckBoxOff brush does not work as you expect, because the check mark is not a separate element with a separate color.

    If you want to change this, you will have to adapt the control templates that can be found in the GitHub repository. You would have to copy the default templates and styles to create a separate check mark and background path and set their colors accordingly. After that, you would include these styles in a resource dictionary and use them as named resources or create implicit styles and override the styles provied by MaterialDesign for the CheckBox.