0

I have a datagrid with a SDate column that shows the Date. I would like to create a triger in Xaml that turns the row green when a date is a certain value. I have this working perfectly:

<DataTrigger Binding="{Binding SDate}" Value="30/12/2016">
       <Setter Property="Background" Value="Green"/>
</DataTrigger>

I would now like to alter this trigger to remove the typed date and replace it with a reference a variable that stores the date instead. The variable is already part of my datacontent. Is that possible? Im 3rd day into WPF and may have lost the plot someplace.

user1500403
  • 551
  • 8
  • 32

2 Answers2

1

You need to write Style Selector for the same.

Have a look at this.

Community
  • 1
  • 1
Mohit Vashistha
  • 1,824
  • 3
  • 22
  • 49
  • 1
    That cannot be done as disscued here http://stackoverflow.com/questions/2240421/using-binding-for-the-value-property-of-datatrigger-condition – Mohit Vashistha Dec 29 '16 at 15:53
  • My bad: You're absolutely right, it's not possible to put a Binding on `DataTrigger.Value`. Unfortunately it won't let me undo the DV until you edit the answer. OTOH a MultiBinding with a comparison converter would still be better than multiple styles. – 15ee8f99-57ff-4f92-890c-b56153 Dec 29 '16 at 15:57
1

I'd do this with a MultiBinding and a multi-value converter:

Converter:

public class DateEqualsConverter : IMultiValueConverter
{
    public object Convert(object[] values, 
        Type targetType, 
        object parameter, 
        CultureInfo culture)
    {
        return System.Convert.ToDateTime(values[0])
            .Equals(System.Convert.ToDateTime(values[1]));
    }

    public object[] ConvertBack(object value, 
        Type[] targetTypes, 
        object parameter, 
        CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Window resources (maybe this is UserControl.Resources instead; you didn't say):

<Window.Resources>
    <local:DateEqualsConverter x:Key="DateEquals" />
</Window.Resources>

And here's the DataTrigger in the Style. I don't know the name of the viewmodel property you're comparing SDate to, so I just called it GreenDate.

OTOH I'm guessing that "The variable is already part of my datacontent" means that the property is already defined in your viewmodel, and your viewmodel is your DataContext. That may be one guess too many. Let me know.

<DataTrigger 
    Value="True"
    >
    <DataTrigger.Binding>
        <MultiBinding Converter="{StaticResource DateEquals}">
            <MultiBinding.Bindings>
                <Binding Path="SDate" />
                <Binding Path="GreenDate" />
            </MultiBinding.Bindings>
        </MultiBinding>
    </DataTrigger.Binding>

    <Setter Property="Background" Value="Green" />
</DataTrigger>