2013-10-20 96 views
0

我有一個程序,其中一個按鈕只應該是活動的,如果相應的userControl有焦點。實現CanExecute MVVM燈使用ICommand

我正在使用MVVM指示燈,並且得到了一個實現ICommand接口的命令。

我已經嘗試過使用Keyboard.FocusedElement,但這不會返回任何內容。

這是命令的代碼(注意,只是返回true,現在得到它的工作,這個SIS當然我正在試圖修復):

class AddItemToNodeCommand<T> : ICommand 
{ 
    public bool CanExecute(object parameter) 
    { 
     Debug.WriteLine("fokuselement er: " + Keyboard.FocusedElement);  
     return true; 
     // throw new NotImplementedException(); 
    } 

    public event EventHandler CanExecuteChanged; 

    public void Execute(object parameter) 
    { 
     Debug.WriteLine("Parameter er: " + parameter); 
     Debug.WriteLine("fokuselement er: " + Keyboard.FocusedElement); 

     //throw new NotImplementedException(); 
    } 
} 

從視圖模型:

public ICommand AddItemToNodeCommand { get; private set; } 
AddItemToNodeCommand = new AddItemToNodeCommand<object>(); 

最後一些XAML的:

<RibbonButton SmallImageSource="../Images/whatever.png" Label="Attribute" Command="{Binding AddItemToNodeCommand}" CommandParameter="Attribute"/> 

我還沒有張貼的XAML的用戶控件,b但想法是,當userControl有焦點時,CanExecute應該是真的..我認爲它可以與Keyboard.FokusedElement一起使用,但我錯了。我能做什麼?

預先感謝您。

+0

你按鈕是你想檢查的用戶控件的子集中嗎? – Nitin

+0

不,按鈕是另一個用戶控件(一個功能區控件)的一部分 –

+0

從功能的角度來看,我認爲只要從userControl移動焦點,那麼該按鈕將被禁用。所以我不認爲按鈕在功能上仍然有用。糾正我,如果我不明白你的問題。 –

回答

0

似乎Keyboard.FocusedElement是有點狡猾。

查看here解決方案涉及附加行爲並覆蓋Keyboard.GotKeyboardFocusEvent。我試過了,它似乎工作。

否則,您可以綁定到IsKeyboardFocusedIsKeyboardFocusWithin。只要把這個在您的XAML的一個簡單的例子:

<StackPanel> 
<TextBox Name="test_txtbx" >Hullo</TextBox> 
    <TextBox Name="test_txtbx_2">Hullo 2</TextBox> 
    <Label Content="{Binding ElementName=test_txtbx, Path=IsKeyboardFocused}"></Label> 
    <Label Content="{Binding ElementName=test_txtbx_2,Path=IsKeyboardFocusWithin }"></Label> 
    <Button Click="TestClick">test me </Button> 
</StackPanel> 

標籤顯示如果匹配的文本框具有焦點。

(這裏有一個old article,它表示重點也很有趣,不過如果仍然相關的話,dunno也是如此)。