是否可以在运行时将数据触发器附加到样式?我现在经历了几次(非工作)代码,似乎无法找到我出错的地方。
这是我用来附加样式和触发器的方法:
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 :(得分:2)
我非常确定绑定刚刚破解,我在代码中创建了类似的样式并且它们起作用。
特别是这条线看起来很可疑:
b.ElementName = this.SecondaryOptions[ctrl.Name];
(如果你想绑定到控件本身,请使用RelativeSource。)
您是否检查过VisualStudio的输出窗口是否存在绑定错误?