2011-03-17 77 views
4

我有,現在我的WPF應用程序還挺可怕的問題...自定義用戶控件「的IsEnabled」數據綁定不工作

我已經使用編輯器部件的細節自定義用戶控件。它應該從未啓用開始,並在用戶選擇要編輯的組件時立即啓用。

問題是:IsEnabled屬性甚至沒有改變。

這裏是我的代碼:

<my:UcComponentEditor Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
         IsEnabled="{Binding EditorEnabled}" 
           DataContext="{Binding VmComponent}" /> 

EditorEnabled是在我的視圖模型(VmComponent)的屬性,並且默認爲false,當用戶選擇了一個組件或創建一個

只是爲了成爲真正的記錄,在我的ViewModel:

private Boolean _editorEnabled = false; 

    public Boolean EditorEnabled 
    { 
     get { return _editorEnabled; } 
     set 
     { 
      _editorEnabled = value; 
      OnPropertyChanged("EditorEnabled"); 
     } 
    } 

當我嘗試啓動我的應用程序時,UserControl啓動...啓用。 我在所有地方添加了斷點,EditorEnabled從一開始就是錯誤的。

我也做了一個可怕的愚蠢的事情,試圖找出發生了什麼:我創建了一個轉換器(如此有用 - 將布爾轉換爲布爾 - 呃),把一個斷點,並... ...代碼永遠不會到達。

<my:UcComponentEditor Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
         IsEnabled="{Binding EditorEnabled, Converter={StaticResource BoolConverter}}" 
           DataContext="{Binding VmComponent}" /> 

這可能意味着屬性isEnabled從不設置,因爲轉換器永遠不會到達。

您是否在那裏看到任何問題?我開始在WPF工作大約一個星期前,因此我可能錯過了一些重要的...

非常感謝您的寶貴時間:-)

+0

斷點停在'_editorEnabled = value;'? – 2011-03-17 12:05:08

+0

正確創建了VmComponent?據我所知,該綁定不會初始化一個新的對象。 – Harry 2011-03-17 12:18:56

+0

@Fun Mun Pieng:是的,它通過了setter @Harry:是的,VmComponent被創建,並且適合所有其他需求,只有這個不工作 – Damascus 2011-03-17 12:53:02

回答

2

您應該添加的DependencyProperty的結合才能正常工作。 See here for more information.

代碼隱藏:

public static readonly DependencyProperty EditorEnabledDependencyProperty = DependencyProperty.Register("EditorEnabled", typeof(bool), typeof(UcComponentEditor), new PropertyMetadata(false)); 

public bool EditorEnabled 
{ 
    get { return (bool)base.GetValue(UcComponentEditor.EditorEnabledDependencyProperty); } 
    set { base.SetValue(UcComponentEditor.EditorEnabledDependencyProperty, value); } 
} 
+0

真的值得添加嗎?我的意思是,該控件自然具有IsEnabled屬性。我認爲添加一個與IsEnabled具有相同角色的DependencyProperty會導致錯誤編碼: -/ – Damascus 2011-03-17 12:46:23

+0

是 - 依賴屬性在XAML中大量使用 - 請參閱我發佈的鏈接以獲取更多信息。我用一個例子更新了我的答案。 – 2011-03-17 12:52:43

+0

不,不需要添加DependencyProperty - 代碼看起來應該像現在這樣工作。我會嘗試顯式設置datacontext - 或者對VmComponent屬性進行屬性更改 - 或者在InitializeComponent之前設置屬性值。 – 2011-03-17 12:58:44

1

我認爲這個問題是,有用戶控件的DataContext屬性綁定。這意味着EditorEnabled屬性應該是VmComponent對象中的一個屬性。至少這就是我的問題所在。

爲了解決這個問題,我給IsEnabled的綁定指定了一個合適的源。一旦我做到了,控制開始按預期工作。

希望有所幫助。

0

將控件封裝在DockPanel中(例如)不需要DependencyProperty。

然後,您可以簡單地使用dockpanel而不是自定義控件進行綁定。