Search code examples
c#wpfhashcodecontroltemplatedatatrigger

How to write a DataTrigger based on hashcode of a Control in WPF


I have a property HashCodeValue. Based on HashCode in the HashCodeValue property I need to change the visibility of the Control using a DataTrigger.

The WPF XAML source code:

<Style TargetType="{x:Type DataGridColumnHeader}" x:Key="DummyFilterDataGridColumnHeader">
   <Setter Property="Template">
      <Setter.Value>
          <ControlTemplate TargetType="{x:Type DataGridColumnHeader}">
              <Button Content="Super I" Visibility="Collapsed" />
              <Button Content="Super II" Visibility="Collapsed" />
              <Button Content="Super III" Visibility="Collapsed" />
              <ControlTemplate.Triggers>
                    <DataTrigger Property="{Binding HashCodeValue}" Value="???">
                        <Setter TargetName="Button" Property="Visibility" Value="Visible" />
                    </DataTrigger>
              </ControlTemplate.Triggers>
          </ControlTemplate>
      </Setter.Value>
   </Setter>
</Style>

We can't know the HashCode at compile time, it is generated only on at run time. Out of three buttons, the property holds any one of the buttons' HashCode at run time. Based on the value, I want to change the Visibility of the corresponding button to Visible.

Kindly assist me how to write the DataTrigger for my scenario.


Solution

  • Since Hashcode value is known only at runtime, i think, you should use IValueConverter to reach your goal. Basic idea is that you have hash as converter value, some additional string as converter parameter, getting bool as converter output.

    So, your code might look like this:

     <ControlTemplate.Triggers>
                        <DataTrigger Property="{Binding HashCodeValue,Converter={StaticResource myConverter,ConverterParameter=myparameter}}" Value="true">
                            <Setter TargetName="Button" Property="Visibility" Value="Visible" />
                        </DataTrigger>
                  </ControlTemplate.Triggers>
    

    This trick will give you what you need, if i understood you correctly.