Sonny Boy
Sonny Boy

Reputation: 8016

Attaching DataTriggers at runtime

Is it possible to attach datatriggers to a style at runtime? I've been through my (non-working) code a few times now and can't seem to find where I've gone wrong.

Here's the method I use to attach the style and trigger:

private void AttachVisibilityTrigger(Control ctrl)
{
    Style stl = new System.Windows.Style();
    DataTrigger dt = new DataTrigger();
    PropertyInfo pi = _entity.GetType().GetProperty(this.SecondaryOptions[ctrl.Name]);
    Type controlType = this.GetControlTypeForProperty(ref dt, pi); //gets the control type based on the property name and then sets the value for the DataTrigger for which I want the visibility to be hidden
    Binding b = this.GetVisibilityBindingByControlType(controlType); //returns a new Binding with the appropriate Path set that corresponds to the bound property value (e.g IsChecked for CheckBoxes, Text for TextBoxes, SelectedValue for Comboboxes, etc)

    b.ElementName = this.SecondaryOptions[ctrl.Name];
    dt.Binding = b;
    dt.Setters.Add(new Setter(Control.VisibilityProperty, System.Windows.Visibility.Hidden));

    stl.Triggers.Add(dt);
    ctrl.Style = stl;
}

Upvotes: 1

Views: 298

Answers (1)

brunnerh
brunnerh

Reputation: 185290

I'm pretty sure the binding is just broken, i created similar styles in code and they work.

Especially this line looks quite suspicious:

b.ElementName = this.SecondaryOptions[ctrl.Name];

(If you want to bind to the control itself use RelativeSource instead.)

Have you checked the Output window of VisualStudio for binding errors?

Upvotes: 2

Related Questions