wpf XAML 中有没有办法在双击时选择文本框中的所有文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16041556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:36:47  来源:igfitidea点击:

Is there a way in XAML to select all text in textbox when double clicked?

c#wpfxaml

提问by KeyboardFriendly

Is there a way to highlight all text in textbox purely through XAML, or does it have to be done in the Xaml.cs

有没有办法纯粹通过 XAML 突出显示文本框中的所有文本,还是必须在 Xaml.cs 中完成

Thanks!

谢谢!

回答by Farhad Jabiyev

This is what you are going to do:

这就是你要做的:

First, add DoubleClickBehavior.csclass to your Project.

首先,将DoubleClickBehavior.cs类添加到您的项目中。

class DoubleClickBehavior : Behavior<TextBox>
    {
        protected override void OnAttached()
        {
            AssociatedObject.MouseDoubleClick += AssociatedObjectMouseDoubleClick;
            base.OnAttached();
        }

        protected override void OnDetaching()
        {
            AssociatedObject.MouseDoubleClick -= AssociatedObjectMouseDoubleClick;
            base.OnDetaching();
        }

        private void AssociatedObjectMouseDoubleClick(object sender, RoutedEventArgs routedEventArgs)
        {
            AssociatedObject.SelectAll();
        }
    }

Then in .xaml, add this behavior to your TextBox:

然后在 中.xaml,将此行为添加到您的 TextBox:

<TextBox>
        <i:Interaction.Behaviors>
            <local:DoubleClickBehavior/>
        </i:Interaction.Behaviors>
</TextBox>

You need to add two namepsaces to your .xamlto use your behavior. (The name of my project was WpfApplication1, so you will probably need to change that):

您需要为.xaml您的行为添加两个命名空间。(我的项目名称是WpfApplication1,因此您可能需要更改它):

 xmlns:local ="clr-namespace:WpfApplication1" 
 xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

That's it. Also you need System.Windows.Interactivity.dllto use the Behaviorclass.

就是这样。您还需要System.Windows.Interactivity.dll使用Behavior该类。

You can download it from the Nuget Package Manager.

您可以从Nuget 包管理器下载它。

回答by Bob.

With a TextBox, you can add the PreviewMouseDoubleClickevent.

使用 TextBox,您可以添加PreviewMouseDoubleClick事件。

<TextBox DockPanel.Dock="Top" Name="MyTextBox" AcceptsReturn="True" PreviewMouseDoubleClick="TextBoxSelectAll"/>

Then you set the TextBox.SelectedText Propertyof the TextBoxto the text in the TextBox.

然后,设置TextBox.SelectedText属性TextBox在文本TextBox

private void TextBoxSelectAll(object sender, MouseButtonEventArgs e) {
    // Set the event as handled
    e.Handled = true;
    // Select the Text
    (sender as TextBox).SelectAll();
}