-1

What's the equivelant of this DataTrigger in C# code?

<DataTrigger
  Binding="{Binding}"
  Value="{x:Null}">
    <Setter
      Property=SomeProperty
      Value=SomeValue />
</DataTrigger>

I am skeptical on how to create the Binding. Is this correct?

var trigger = new DataTrigger();
trigger.Value = null;
// Is this sufficient?
trigger.Binding = new Binding();
// Code to create the setter
// ...
7
  • You should have searched first before posting your question. social.msdn.microsoft.com/Forums/vstudio/en-US/… Commented Sep 9, 2021 at 17:42
  • I've seen this link. It's the Binding="{Binding}" that I don't know how to create. Commented Sep 9, 2021 at 17:45
  • 1
    trigger.Binding = new Binding("."); should be equivalent. However, neither that nor Binding="{Binding}" makes sense on a DataTrigger, because it lacks a source property that could be updated and thus trigger the Trigger. Commented Sep 9, 2021 at 18:16
  • 1
    A binding (created in XAML) without a Path (or a Path with value '.') will still have a the DataContext as implict Source. And the DC can change from null to not null. So in XAML it would work - on DataContextChanged event. In code behind, I think the Source must be actively, explictly set, otherwise the trigger has a no Source or null as its Source and the condition will always be true. Commented Sep 9, 2021 at 21:53
  • 1
    Could be when the trigger is added to a FrameworkElement's style and thus becomes part of the visual tree, the current DataContext potentially could also automatically become the Source (of the triggers Binding). Testing is above studying, as they say. Commented Sep 9, 2021 at 22:01

1 Answer 1

1

This would be the equivalent of your XAML:

var trigger = new DataTrigger()
{
    Value = null,
    Binding = new Binding(".")
};
trigger.Setters.Add(new Setter() { Property = SomeProperty, Value = SomeValue });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.