2011-02-16 3 views
4

바운드 데이터 소스를 기반으로 KeyBinding을 동적으로 정의 할 수 있습니까? 그리드가있는 화면이 있으며 사용자가 다양한 레이아웃을 저장할 수 있습니다. 나는 현재 ViewModel을 통해 레이아웃 이름에 그리드 컨텍스트 메뉴를 바인딩하여 메뉴를 통해 레이아웃을 전환 할 수 있습니다.WPF에서 동적으로 KeyBinding 추가

그러나 각 레이아웃을 바로 가기 키와 연결하고 싶습니다. 바로 가기 키가 사용자에 의해 정의 되었기 때문에 XAML 창에 여러 개의 요소 (<KeyBinding>)를 추가 할 수는 없습니다. 또 다른 문제는 바인딩이 명령 매개 변수로 레이아웃의 이름을 제공해야한다는 것입니다.

동적 소스에서 일련의 <KeyBinding> 요소를 동적으로 만드는 방법이 있습니까?

테스트로 내보기 XAML에 정적 바인딩을 추가 한 그들은 잘 작동하지만, 이것은 단지 내 개념을 테스트했다 : 것을 할 수있는 몇 가지 방법, IMO에서 가장 쉬운 일이있다

<UserControl.InputBindings> 
    <KeyBinding Key="F7" Command="{Binding MyCommand}" CommandParameter="My Layout Name"/> 
    <KeyBinding Key="F8" Command="{Binding MyCommand}" CommandParameter="My Other Layout Name"/> 
</UserControl.InputBindings> 

답변

0

명령 이름에 따라 키를 반환하는 변환기를 만드는 것입니다 (본질적으로 레이아웃 이름은 키이고 키는 값임). 좀 더 복잡한 guestures을 처리해야하는 경우가 약간 더 복잡한거야, 외침을 GIS와 나는 그것을위한 샘플 공예 것이다 : 여기

을 XAML입니다 : 여기

<Grid.InputBindings> 
<KeyBinding Key="{Binding Converter={StaticResource converter}, ConverterParameter=My Other Layout Name}" Command="{Binding MyCommand}" /> 
</Grid.InputBindings> 
+0

당신은 복잡한 guesteres (Ctrl + Alt + _Blah 등)을 처리하기 위해 같은 구현을 사용하여 멀리 얻을 수 있습니다, 참조하십시오 : http://stackoverflow.com/questions/3625859/can-i-create-a-keybinding-for-a-sequence-of-keys-in-wpf –

0

내가 만드는 데 사용하는 코드입니다 단축키에서 스 니펫을 실행할 수 있도록 스 니펫 편집기의 일부로 동적으로 키 바인딩을 사용합니다. 이전의 예에 추가

도 키 콤보의 사용자 입력을 구문 분석하는 방법을 보여줍니다 그것을 :

// example key combo from user input 
var ksc = "Alt+Shift+M"; 
ksc = ksc.ToLower(); 

KeyBinding kb = new KeyBinding(); 

if (ksc.Contains("alt")) 
    kb.Modifiers = ModifierKeys.Alt; 
if (ksc.Contains("shift")) 
    kb.Modifiers |= ModifierKeys.Shift; 
if (ksc.Contains("ctrl") || ksc.Contains("ctl")) 
    kb.Modifiers |= ModifierKeys.Control; 

string key = 
    ksc.Replace("+", "") 
     .Replace("-", "") 
     .Replace("_", "") 
     .Replace(" ", "") 
     .Replace("alt", "") 
     .Replace("shift", "") 
     .Replace("ctrl", "") 
     .Replace("ctl", ""); 

key = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(key); 
if (!string.IsNullOrEmpty(key)) 
{ 
    KeyConverter k = new KeyConverter(); 
    kb.Key = (Key)k.ConvertFromString(key); 
} 

// Whatever command you need to bind to 
// CommandBase here is a custom class I use to create commands 
// with Execute/CanExecute handlers 
kb.Command = new CommandBase((s, e) => InsertSnippet(snippet), 
          (s,e) => Model.IsEditorActive); 

Model.Window.InputBindings.Add(kb); 
+0

그 대부분은 다음과 같이 대체 될 수 있습니다 (모든 것을 수동으로 구문 분석 할 필요가 없습니다.) kb = new KeyBinding (theCommand, 새 KeyGestureConverter(). ConvertFromString (ksc)를 KeyGesture로 사용); –

관련 문제