2011-04-25 45 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的輸出窗口綁定錯誤。 ?