WPF Calling method from a DataTrigger

squig picture squig · Jun 15, 2011 · Viewed 8.2k times · Source

Is it possible to use a wild card or call a method to work out if a DataTrigger should be applied?

I currently have my DataList bound to an IEnumerable that contains file names and I want the file names to be greyed out if there files extension starts with "old"

My non-working dream xaml markup looks something like this:

<DataTemplate.Triggers>
    <DataTrigger Binding="{Binding}" Value="*.old*">
        <Setter TargetName="FileName" Property="Foreground" Value="Gray"/>
    </DataTrigger>
</DataTemplate.Triggers>

The only workable solution I've been able to come up with is to insert a new view model property that contains this logic, but I would like to avoid changing the view model if possible.

Answer

Aran Mulholland picture Aran Mulholland · Jun 15, 2011

The answer to both questions is yes....in a roundabout way

If you use a Binding Converter you can pass a parameter to it and have it return a boolean, that would be an effective way to do what you describe.

<DataTemplate.Triggers>
    <DataTrigger Binding="{Binding Path=., Converter={StaticResource myFileExtensionConverter}, ConverterParameter=old}" Value="True">
        <Setter TargetName="FileName" Property="Foreground" Value="Gray"/>
    </DataTrigger>
</DataTemplate.Triggers>

where the converter would look something like this

  public class MyFileExtensionConverter : IValueConverter {  
      public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
         Boolean returnValue = false;  

         String fileExtension = parameter as String;
         String fileName = value as String;

         if (String.IsNullOrEmpty(fileName)) { }
         else if (String.IsNullOrEmpty(fileExtension)) { }
         else if (String.Compare(Path.GetExtension(fileName), fileExtension, StringComparison.OrdinalIgnoreCase) == 0) {
            returnValue = true;
         }
         return returnValue;
      }

      public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
         return value;
      }
   }

basically when the file extension matches you get a "true" which will fire the trigger.