初始焦点和选择所有行为 [英] Initial Focus and Select All behavior

查看:136
本文介绍了初始焦点和选择所有行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户控件嵌套在一个窗口中,作为对话框显示的外壳。我忽略了shell窗口中的焦点,在托管用户控件中,我使用FocusManager将初始焦点设置为一个命名元素(文本框),如下所示。



这个工作,设置光标在指定的文本框的开始;但是我想要所有的文本被选中。

TextBoxSelectionBehavior类(下面)通常是完全正确的,但在这种情况下。是否有一个简单的XAML修复,以获得在初始焦点的指定文本框中的文本?



干杯,

Berryl



文本框选择行为



  //在应用程序启动中
TextBoxSelectionBehavior.RegisterTextboxSelectionBehavior ;

///< summary>
///帮助者选择条目
上的文本框中的所有文本///< / summary>
public static class TextBoxSelectionBehavior
{
public static void RegisterTextboxSelectionBehavior()
{
EventManager.RegisterClassHandler(typeof(TextBox),UIElement.GotFocusEvent,new RoutedEventHandler(OnTextBox_GotFocus) );


private static void OnTextBox_GotFocus(object sender,RoutedEventArgs e)
{
var tb =(sender as TextBox);
if(tb!= null)
tb.SelectAll();


$ / code $ / $ p

托管的UserControl



 < UserControl 
< DockPanel KeyboardNavigation.TabNavigation =Local
FocusManager.FocusedElement ={Binding ElementName = tbLastName}> ;

< TextBox x:Name =tbLastName... />



止损解决方案



Rachel下面,我放弃了FocusManger,赞成一些后面的代码:

  tbLastName.Loaded + =(sender,e)=> ; tbLastName.Focus(); 

还是会喜欢简单和普通杂项的声明式方法...我通常使用 AttachedProperty 来使文本框突出显示其焦点上的文本。它被用来像

 < TextBox local:HighlightTextOnFocus =True/> 

所附属性代码

  public static readonly DependencyProperty HighlightTextOnFocusProperty = 
DependencyProperty.RegisterAttached(HighlightTextOnFocus,
typeof(bool),typeof(TextBoxProperties),
new PropertyMetadata(false,HighlightTextOnFocusPropertyChanged) );

$ b $ AttachedPropertyBrowsableForChildrenAttribute(IncludeDescendants = false)]
[AttachedPropertyBrowsableForType(typeof(TextBox))]
public static bool GetHighlightTextOnFocus(DependencyObject obj)
{
return(bool)obj.GetValue(HighlightTextOnFocusProperty);


public static void SetHighlightTextOnFocus(DependencyObject obj,bool value)
{
obj.SetValue(HighlightTextOnFocusProperty,value);


private static void HighlightTextOnFocusPropertyChanged(
DependencyObject obj,DependencyPropertyChangedEventArgs e)
{
var sender = obj as UIElement; (bool)e.NewValue)
{
sender.GotKeyboardFocus + = OnKeyboardFocusSelectText;
if(sender!= null)
{
if
sender.PreviewMouseLeftButtonDown + = OnMouseLeftButtonDownSetFocus;
}
else
{
sender.GotKeyboardFocus - = OnKeyboardFocusSelectText;
sender.PreviewMouseLeftButtonDown - = OnMouseLeftButtonDownSetFocus;



$ b private static void OnKeyboardFocusSelectText(
object sender,KeyboardFocusChangedEventArgs e)
{
var textBox = e.OriginalSource作为TextBox;
if(textBox!= null)
{
textBox.SelectAll();



private static void OnMouseLeftButtonDownSetFocus(
object sender,MouseButtonEventArgs e)
{
TextBox tb = FindAncestor< TextBox>( (DependencyObject的)e.OriginalSource);

if(tb == null)
return;

if(!tb.IsKeyboardFocusWithin)
{
tb.Focus();
e.Handled = true;



static T FindAncestor< T>(DependencyObject current)
其中T:DependencyObject
{
current = VisualTreeHelper.GetParent (当前); (current!= null)
{
if(current是T)
{
return(T)current;


}
current = VisualTreeHelper.GetParent(current);
};
返回null;

编辑

根据下面的评论,那么摆脱 FocusManager.FocusedElement 和设置 tb.Focus()您的文本框的已加载事件中的code>和 tb.SelectAll()


I have a user control that is nested inside a window that is acting as a shell for a dialog display. I ignore focus in the shell window, and in the hosted user control I use the FocusManager to set the initial focus to a named element (a textbox) as shown below.

This works, setting the cursor at the beginning of the named textbox; however I want all text to be selected.

The TextBoxSelectionBehavior class (below) usually does exactly that, but not in this case. Is there an easy xaml fix to get the text in the named textbox selected on initial focus?

Cheers,
Berryl

TextBox Selection Behavior

// in app startup
TextBoxSelectionBehavior.RegisterTextboxSelectionBehavior();

/// <summary>
/// Helper to select all text in the text box on entry
/// </summary>
public static class TextBoxSelectionBehavior
{
    public static void RegisterTextboxSelectionBehavior()
    {
        EventManager.RegisterClassHandler(typeof(TextBox), UIElement.GotFocusEvent, new RoutedEventHandler(OnTextBox_GotFocus));
    }

    private static void OnTextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        var tb = (sender as TextBox);
        if (tb != null)
            tb.SelectAll();
    }
}

The hosted UserControl

<UserControl   
<DockPanel KeyboardNavigation.TabNavigation="Local" 
    FocusManager.FocusedElement="{Binding ElementName=tbLastName}" >

            <TextBox x:Name="tbLastName" ... />

stop gap solution

Per comments with Rachel below, I ditched the FocusManger in favor of some code behind:

tbLastName.Loaded += (sender, e) => tbLastName.Focus();

Still would love a declarative approach for a simple and common chore though...

解决方案

I usually use an AttachedProperty to make TextBoxes highlight their text on focus. It is used like

<TextBox local:HighlightTextOnFocus="True" />

Code for attached property

public static readonly DependencyProperty HighlightTextOnFocusProperty =
    DependencyProperty.RegisterAttached("HighlightTextOnFocus", 
    typeof(bool), typeof(TextBoxProperties),
    new PropertyMetadata(false, HighlightTextOnFocusPropertyChanged));


[AttachedPropertyBrowsableForChildrenAttribute(IncludeDescendants = false)]
[AttachedPropertyBrowsableForType(typeof(TextBox))]
public static bool GetHighlightTextOnFocus(DependencyObject obj)
{
    return (bool)obj.GetValue(HighlightTextOnFocusProperty);
}

public static void SetHighlightTextOnFocus(DependencyObject obj, bool value)
{
    obj.SetValue(HighlightTextOnFocusProperty, value);
}

private static void HighlightTextOnFocusPropertyChanged(
        DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
    var sender = obj as UIElement;
    if (sender != null)
    {
        if ((bool)e.NewValue)
        {
            sender.GotKeyboardFocus += OnKeyboardFocusSelectText;
            sender.PreviewMouseLeftButtonDown += OnMouseLeftButtonDownSetFocus;
        }
        else
        {
            sender.GotKeyboardFocus -= OnKeyboardFocusSelectText;
            sender.PreviewMouseLeftButtonDown -= OnMouseLeftButtonDownSetFocus;
        }
    }
}

private static void OnKeyboardFocusSelectText(
    object sender, KeyboardFocusChangedEventArgs e)
{
    var textBox = e.OriginalSource as TextBox;
    if (textBox != null)
    {
        textBox.SelectAll();
    }
}

private static void OnMouseLeftButtonDownSetFocus(
    object sender, MouseButtonEventArgs e)
{
    TextBox tb = FindAncestor<TextBox>((DependencyObject)e.OriginalSource);

    if (tb == null)
        return;

    if (!tb.IsKeyboardFocusWithin)
    {
        tb.Focus();
        e.Handled = true;
    }
}

static T FindAncestor<T>(DependencyObject current)
    where T : DependencyObject
{
    current = VisualTreeHelper.GetParent(current);

    while (current != null)
    {
        if (current is T)
        {
            return (T)current;
        }
        current = VisualTreeHelper.GetParent(current);
    };
    return null;
}

Edit

Based on comments below, what about just getting rid of the FocusManager.FocusedElement and setting tb.Focus() and tb.SelectAll() in the Loaded event of your TextBox?

这篇关于初始焦点和选择所有行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆