2011-04-25 46 views
1

是否可以在运行时将数据触发附加到样式?我已经通过我的(非工作)代码几次了,似乎无法找到我出错的地方。在运行时附加DataTriggers

这是我使用附加的样式和触发器的方法:

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; 
} 
+0

为什么你需要这样做?有没有办法用数据模板来做到这一点?另外:你是否使用调试器完成了它,反射是否成功,创建的绑定是否有意义? – 2011-04-25 19:52:17

+0

我需要这个,因为我有一个窗口处理创建我的项目中的所有新对象。窗口上的控件是在运行时根据每个对象的属性的数据类型生成的。现在我已经被要求阻止某些值的输入,直到首先提供其他值。例如,“财产是否损坏?如果是,描述”。所以我有一个布尔IsDamaged属性的复选框,如果选中,我希望绑定到DamageDescription属性的文本框现在可见。 – 2011-04-25 20:00:41

+0

“处理所有新对象创建的单个窗口”听起来很奇怪。无论如何,正如我之前指出的那样,您是否可以确认绑定创建已解决?因为其他人看起来对我来说很好,我不知道你在那里使用什么物体和领域。 – 2011-04-25 20:04:53

回答

2

我敢肯定的绑定刚刚破,我创建了类似的代码风格和他们的工作。

特别是这一行看起来很可疑:

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

如果你希望绑定到自己使用的RelativeSource代替控制。)

你检查的VisualStudio的输出窗口绑定错误。 ?