Search code examples
c#wpfxamldata-bindingdatatrigger

How to create a DataTrigger programatically with Binding="{Binding}"?


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
// ...

Solution

  • 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 });