C# 在运行时附加数据触发器

C# 在运行时附加数据触发器,c#,wpf,binding,styles,datatrigger,C#,Wpf,Binding,Styles,Datatrigger,是否可以在运行时将datatriggers附加到样式?我已经检查过我的(非工作)代码几次了,但似乎找不到哪里出了问题 下面是我用来附加样式和触发器的方法: private void AttachVisibilityTrigger(Control ctrl) { Style stl = new System.Windows.Style(); DataTrigger dt = new DataTrigger(); PropertyInfo pi = _entity.GetTy

是否可以在运行时将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;
}

我很确定绑定已经被破坏了,我在代码中创建了类似的样式,它们都可以工作

尤其是这句话看起来很可疑:

b.ElementName = this.SecondaryOptions[ctrl.Name];
(如果要绑定到控件本身,请改用RelativeSource。)


是否检查了VisualStudio的输出窗口中的绑定错误?

为什么需要执行此操作?是否没有办法使用数据模板?另外:您是否使用调试器逐步完成了它,反射是否有效,创建的绑定是否有意义?我需要这样做,因为我有一个窗口来处理项目中所有新对象的创建。窗口上的控件在运行时根据每个对象的属性数据类型生成。我现在得到一个要求,在第一次提供其他值之前,防止输入某些值。例如,“财产是否损坏?如果是,请描述”。因此,我有一个布尔IsDamage属性的复选框,如果选中,我希望绑定到DamageDescription属性的文本框现在可见。“一个处理所有新对象创建的单一窗口”听起来很奇怪。无论如何,正如我之前提到的,您能确认绑定创建工作正常吗?因为其余的对我来说似乎没有问题,我不知道你在那里使用了什么对象和字段。反射在调试器中被检出(至少我认为是这样)。我实例化的所有对象和所有设置的属性似乎都是有序的。在运行时,我选中复选框,但什么也没有发生。