2014-01-23 2 views
0

나는 제어 여기내 컨트롤을 포커스 할 수있게 만드는 방법?

public class FocusTestControl : Control { 
    public FocusTestControl() { 
     DefaultStyleKey = typeof(FocusTestControl); 
    } 
} 

을 가지고있다가 기본 스타일

<Style 
    TargetType="local:FocusTestControl"> 
    <Setter 
     Property="Focusable" 
     Value="True" /> 
    <Setter 
     Property="Template"> 
     <Setter.Value> 
      <ControlTemplate> 
       <Grid> 
        <Border 
         Background="AliceBlue" /> 
       </Grid> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

의 나는 창에서이 컨트롤을 넣어 :

<Window 
x:Class="MakeWpfControlFocusable.MainWindow" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="clr-namespace:MakeWpfControlFocusable" 
Title="MainWindow" 
Height="350" 
Width="525"> 
<Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition /> 
     <RowDefinition 
      Height="35" /> 
    </Grid.RowDefinitions> 
    <local:FocusTestControl /> 
    <StackPanel 
     Grid.Row="1" 
     Orientation="Horizontal"> 
     <TextBlock 
      Text="Focused element: " /> 
     <TextBlock 
      Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=KeyboardFocusedElement}" /> 
     <TextBox 
      Text="Text" /> 
    </StackPanel> 
</Grid> 

그러나 컨트롤을 클릭하면 '아무튼 초점 맞추기 (KebordFocus)

사실, 내 작업은 KeyDown 및 KeyUp 이벤트를 처리합니다. 그러나 요소에 키 코드 포커스가 없을 때는 불가능합니다.

답변

1

키 키보드 포커스는 Tab 키보드 키를 눌러서 설정할 수 있습니다. 하지만 컨트롤을 클릭하면 설정되지 않습니다. MouseDown 이벤트를 구독하고 핸들러에서 수동으로 포커스를 설정했습니다.

public class FocusTestControl : Control, IInputElement { 


    public FocusTestControl() { 
     DefaultStyleKey = typeof(FocusTestControl); 
     MouseDown += FocusTestControl_MouseDown; 
    } 

    void FocusTestControl_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { 
     Keyboard.Focus(this); 
    } 
} 
관련 문제