2017-12-20 36 views
-1

문자열을 기반으로 프로그래밍 방식으로 KeyBinding 명령을 추가하는 방법은 무엇입니까? 내 xaml 코드에는 다음과 같은 속성이 있습니다.프로그래밍 방식으로 KeyBindings 명령 추가

<KeyBinding Key="Q" Command="{Binding AcceptAndNextCommand}" /> 

이 잘 작동하지만 동적으로 키 바인딩의이 종류를 추가 할 수 있도록하고 싶습니다 그래서 내가 프로그램을 추가 할 수 있어야합니다. 내 KeyBindings 각각이 별도의 행인 프로젝트 설정 파일을 만들었습니다. 이 행은 각 키보드 키를 사전 키로 저장하고 각 명령을 사전 값으로 저장 한 사전 값을 가지고 있습니다. 예 : {"Key":"Q", "Value":"AcceptAndNextCommand"}. A String to KeyBinding 키 변환은 정상적으로 작동하지만 String에 기반한 KeyBinding에 명령을 추가하는 방법을 모르겠습니다. 사전 값의 모든 명령 문자열은이 "AcceptAndNextCommand"와 같습니다. 아래 예제에서와 같이 CommandConverter cv으로이 작업을 수행 할 수 있기를 기대했지만 작동하지 않는 것 같습니다.

private void KeyboardShortcuts() 
    { 
     foreach (SettingsProperty property in Properties.KeyboardBindings.Default.Properties) 
     { 
      var propertyValue = JsonConvert.DeserializeObject<Dictionary<string, string>>(
       Properties.KeyboardBindings.Default[property.Name].ToString()); 

      var keyBinding = new KeyBinding() 
      { 
       Key = (Key)new KeyConverter().ConvertFromString(propertyValue["Key"]) 
      }; 

      CommandConverter cv = TypeDescriptor.GetConverter(typeof(ICommand)) as CommandConverter; 
      keyBinding.Command = (ICommand)cv?.ConvertFromString(propertyValue["Command"]); 
     } 
    } 

나는 다음과 같은 question 내 구현을 기반으로하지만, 매우 잘 명령의 추가 설명하지 않았다.

답변

1

프로그래밍 방식으로 바인딩을 만들 수 BindingOperations.SetBinding 방법을 사용할 수 있습니다

KeyBinding kb = new KeyBinding(); 
BindingOperations.SetBinding(kb, KeyBinding.CommandProperty, new Binding("AcceptAndNextCommand")); 
... 
InputBindings.Add(kb); 

바인딩의 경로는 단지 string입니다.

+0

보기에서 키 바인딩을 설정하지 않았습니까? 나는 방금 도망 쳤고 어떤 오류도 던지지 않았고 아무 일도 일어나지 않았다. –

+0

보기에서? SetBinding 메서드에 전달하는 KeyBinding의 명령을 설정합니다. 물론 프로그래밍 방식으로 만드는 KeyBinding을 어떻게 든 뷰에 추가해야합니다. 아니면 어디에서 KeyBinding을 사용할 계획입니까? – mm8

+0

그것이 내 의견에 의미하는 바입니다. 키 바인딩을 사용해야하는보기에 어떻게 추가합니까? –