c# - MVVM-如何在文本框中选择文本?

标签 c# wpf mvvm textbox mvvm-light

是否有 MVVM 方法来选择文本框中的文本?我使用的 MVVM 框架是 Laurent Bugnion 的 MVVM Light Toolkit。

最佳答案

每当我试图直接影响“纯”MVVM 应用程序( View 中没有代码隐藏)中的 View 时,我将使用 Attached Properties封装我想要达到的任何效果。我将创建一个界面来定义我希望使用自定义事件执行的操作。然后,我在将在 View 上“运行”这些命令的每个 ViewModel 中实现此接口(interface)。最后,我将 ViewModel 绑定(bind)到 View 定义中的附加属性。以下代码显示了如何为 SelectAll 和 TextBox 执行此操作。可以轻松扩展此代码以对 View 中的任何组件执行几乎任何操作。

我的附加属性和接口(interface)定义:

using System.Windows;
using System.Windows.Controls;
using System;
using System.Collections.Generic;

namespace SelectAllSample
{
    public static class TextBoxAttach
    {
        public static readonly DependencyProperty TextBoxControllerProperty = DependencyProperty.RegisterAttached(
            "TextBoxController", typeof(ITextBoxController), typeof(TextBoxAttach),
            new FrameworkPropertyMetadata(null, OnTextBoxControllerChanged));
        public static void SetTextBoxController(UIElement element, ITextBoxController value)
        {
            element.SetValue(TextBoxControllerProperty, value);
        }
        public static ITextBoxController GetTextBoxController(UIElement element)
        {
            return (ITextBoxController)element.GetValue(TextBoxControllerProperty);
        }

        private static readonly Dictionary<ITextBoxController, TextBox> elements = new Dictionary<ITextBoxController, TextBox>();
        private static void OnTextBoxControllerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var element = d as TextBox;
            if (element == null)
                throw new ArgumentNullException("d");

            var oldController = e.OldValue as ITextBoxController;
            if (oldController != null)
            {
                elements.Remove(oldController);
                oldController.SelectAll -= SelectAll;
            }

            var newController = e.NewValue as ITextBoxController;
            if (newController != null)
            {
                elements.Add(newController, element);
                newController.SelectAll += SelectAll;
            }
        }
        private static void SelectAll(ITextBoxController sender)
        {
            TextBox element;
            if (!elements.TryGetValue(sender, out element))
                throw new ArgumentException("sender");
            element.Focus();
            element.SelectAll();
        }
    }

    public interface ITextBoxController
    {
        event SelectAllEventHandler SelectAll;
    }

    public delegate void SelectAllEventHandler(ITextBoxController sender);
}

我的 ViewModel 定义:

public class MyViewModel : ITextBoxController
{
    public MyViewModel()
    {
        Value = "My Text";
        SelectAllCommand = new RelayCommand(p =>
        {
            if (SelectAll != null)
                SelectAll(this);
        });
    }

    public string Value { get; set; }
    public RelayCommand SelectAllCommand { get; private set; }

    public event SelectAllEventHandler SelectAll;
}

我的 View 定义:

<Window x:Class="SelectAllSample.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:loc="clr-namespace:SelectAllSample"
    Title="Window1" Height="150" Width="150">
    <x:Code><![CDATA[
        public Window1()
        {
            InitializeComponent();
            DataContext = new MyViewModel();
        }
    ]]></x:Code>
    <StackPanel>
        <TextBox Text="{Binding Value}" loc:TextBoxAttach.TextBoxController="{Binding}" />
        <Button Content="Select All" Command="{Binding SelectAllCommand}" />
    </StackPanel>
</Window>

注意:感谢 Josh Smith 的 RelayCommand(参见图 3 中的代码,位于 this page 上)。在此示例中,它用在 MyViewModel 中(以及几乎所有我的 MVVM 代码)。

关于c# - MVVM-如何在文本框中选择文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2596757/

相关文章:

c# - EF Core,通过从字符串进行 int 转换在 SQL 服务器上执行

c# - Stream写字符串和byte[]数组?

WPF:将 DateTime 类型的 viewmodel 属性绑定(bind)到 ItemsControl 中的 Calendar

c# - XAML 菜单项可见但不可选择?

swift - ReactiveCocoa 内存泄漏 - UIButton 的 CocoaAction 阻止 MVVM 对象反初始化

C#.Net4 : Properly disposing (dynamic) COM objects

javascript - 在 GCharts 的 pdf 生成上替代 headless 浏览器

wpf - 无应用程序对象模式下的 Caliburn micro,就像在 AutoCAD dll 插件中一样

ios - RACSignal 和一系列 View 模型,有没有更被动的方式?

iOS:如何使用 MVVM 将模型从 View 模型传递到 View 模型?