2012-02-21 14 views
4

これはオンラインのように見えません。 Xamlですべてのバインディングを手動でリストするのではなく、キーバインドViewModelを使用してコード内にKeybindingのコレクションを作成し、そのコレクションをビューにバインドする方法を探しています。バインドされたコレクションを持つWindow.InputBindings

私はそれがコードでこの

<Window.InputBindings ItemsSource="{Binding Path=KeybindingList}" /> 

、その後のようなものを見て期待し、リストを持っています。そのようなアプローチは可能ですか?私はどこから始めるのですか?

答えて

6

attached propertyを作成し、その変更をリッスンして、関連付けられたウィンドウのInputBindingsコレクションを変更することができます。

例:

// Snippet warning: This may be bad code, do not copy. 
public static class AttachedProperties 
{ 
    public static readonly DependencyProperty InputBindingsSourceProperty = 
     DependencyProperty.RegisterAttached 
      (
       "InputBindingsSource", 
       typeof(IEnumerable), 
       typeof(AttachedProperties), 
       new UIPropertyMetadata(null, InputBindingsSource_Changed) 
      ); 
    public static IEnumerable GetInputBindingsSource(DependencyObject obj) 
    { 
     return (IEnumerable)obj.GetValue(InputBindingsSourceProperty); 
    } 
    public static void SetInputBindingsSource(DependencyObject obj, IEnumerable value) 
    { 
     obj.SetValue(InputBindingsSourceProperty, value); 
    } 

    private static void InputBindingsSource_Changed(DependencyObject obj, DependencyPropertyChangedEventArgs e) 
    { 
     var uiElement = obj as UIElement; 
     if (uiElement == null) 
      throw new Exception(String.Format("Object of type '{0}' does not support InputBindings", obj.GetType())); 

     uiElement.InputBindings.Clear(); 
     if (e.NewValue == null) 
      return; 

     var bindings = (IEnumerable)e.NewValue; 
     foreach (var binding in bindings.Cast<InputBinding>()) 
      uiElement.InputBindings.Add(binding); 
    } 
} 

これはどのUIElement上で使用することができます。

<TextBox ext:AttachedProperties.InputBindingsSource="{Binding InputBindingsList}" /> 

あなたはそれが非常に凝っになりたい場合は、INotifyCollectionChangedをチェック-入力すると、場合InputBindingsを更新コレクションは変更されますが、古いコレクションなどの登録を解除する必要がありますので、そのように注意する必要があります。

+0

ウィンドウを変更するには、コードビハインドでこれを行う必要があります。私はこれをMVVMパターンで維持しようとしています。 – Tyrsius

+0

@Tyrsius:これはウィンドウのコードにはなく、どのクラスでもかまいません。バインディングで値コンバーターを使用するようなもので、MVVMとは関係ありません。 –

+0

@Tyrsius:アプローチを説明するための例を追加しました。 –

関連する問題