program tip

xaml wpf의 텍스트 상자에 포커스 설정

radiobox 2020. 9. 7. 07:58
반응형

xaml wpf의 텍스트 상자에 포커스 설정


이 포럼에 대한 일부 게시물과 다른 게시물에도 불구하고 .NET Core에 초점을 맞추는 방법을 알려주는 것을 찾을 수 없습니다 TextBox.

많은 레이블과 텍스트 상자가있는 userControl이 있습니다. 양식이로드되면 특정 텍스트 상자에 포커스를두고 싶습니다.

tabIndex를 설정했지만 작동하지 않는 것 같습니다.

어떤 제안?


FocusManager.FocusedElement이 목적으로 연결된 속성을 사용할 수 있습니다 . 다음은 기본적으로 포커스를 TxtB로 설정하는 코드입니다.

<StackPanel Orientation="Vertical" FocusManager.FocusedElement="{Binding ElementName=TxtB}">
    <TextBox x:Name="TxtA" Text="A" />
    <TextBox x:Name="TxtB" Text="B" />
</StackPanel>

TxtB.Focus()XAML에서이 작업을 수행하지 않으려는 경우 코드 숨김에서 사용할 수도 있습니다 .


이 속성을 TextBox에 직접 적용 할 수 있습니다.

<TextBox Text="{Binding MyText}" FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"/>

나는 WPF를 처음 사용하고 위의 예제를 읽었으며 주어진 xaml 코드 예제를 사용하여 텍스트 상자에 포커스를 설정하려고 시도한 비슷한 경험이있었습니다. 즉, 위의 모든 예제가 작동하지 않았습니다.

내가 찾은 것은 페이지 요소에 FocusManager.FocusElement를 배치해야한다는 것입니다. Window를 부모 요소로 사용했다면 이것이 아마 잘 작동 할 것이라고 가정합니다. 어쨌든, 여기 나를 위해 일한 코드가 있습니다.

 <Page x:Class="NameOfYourClass"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  mc:Ignorable="d"
  Title="Title" 
  Height="720"
  Width="915"
  Background="white"
  Loaded="pgLoaded"
  FocusManager.FocusedElement="{Binding ElementName=NameOfYourTextBox}">

  <!-- Create child elements here. -->

  </Page>

초점을 맞추려는 요소를 다음과 같이 바인딩하십시오.

FocusManager.FocusedElement= "{Binding ElementName= Comobox1}"

그리드 또는 그룹 상자 등


FocusManager는 지능적이지 않아서 약간 혼란 스러웠습니다. 전체 속성을 입력했는데 제대로 작동했습니다.

FocusManager.FocusedElement = "{Binding ElementName = MyTextBox}"


Microsoft Visual Studio Enterprise 2015 버전 14.0.23107.0/C#/WPF


For completeness, there is also a way to handle this from code behind (e.g. in the case of controls that, for whatever reason, are created dynamically and don't exist in XAML). Attach a handler to the window's Loaded event and then use the ".Focus()" method of the control you want. Bare-bones example below.

public class MyWindow
{
    private VisualCollection controls;
    private TextBox textBox;

    // constructor
    public MyWindow()
    {
        controls = new VisualCollection(this);
        textBox = new TextBox();
        controls.Add(textBox);

        Loaded += window_Loaded;
    }

    private void window_Loaded(object sender, RoutedEventArgs e)
    {
        textBox.Focus();
    }
}

From experimenting around, the xaml solution

FocusManager.FocusedElement="{Binding ElementName=yourElement}"

seems to work best when you place it in the highest element in the window hierarchy (usually Window, or the Grid you place everything else in)

참고URL : https://stackoverflow.com/questions/2872238/set-the-focus-on-a-textbox-in-xaml-wpf

반응형