WPF Calling method from a DataTrigger
Asked Answered
S

1

8

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.

Spree answered 15/6, 2011 at 1:39 Comment(0)
U
8

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.

Ululate answered 15/6, 2011 at 2:18 Comment(1)
it's funny every time I find myself wanting to "call a method" from xaml the problem can be solved with a converter. If you want multiple parameters (or bindable parameters) you're talking a MultiBinding with a IMultiValueConverter.Ululate

© 2022 - 2024 — McMap. All rights reserved.