开发者

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.VisibilityPropert开发者_StackOverflowy, System.Windows.Visibility.Hidden));

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


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜