WPF TextBox not allowed illegal characters to be input and limit the text length in mvvm

FredGrit發表於2024-07-25
//xaml
<Window x:Class="WpfApp224.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:local="clr-namespace:WpfApp224"
        mc:Ignorable="d" WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TextBox BorderBrush="Black" BorderThickness="5" FontSize="30"  
                 Height="100"  VerticalAlignment="Top">
            <behavior:Interaction.Triggers>
                <behavior:EventTrigger EventName="PreviewTextInput">
                    <behavior:CallMethodAction MethodName="TextBox_PreviewTextInput" TargetObject="{Binding}"/>
                </behavior:EventTrigger>
                <behavior:EventTrigger EventName="TextChanged">
                    <behavior:CallMethodAction MethodName="TextBox_TextChanged" TargetObject="{Binding}"/>
                </behavior:EventTrigger>
            </behavior:Interaction.Triggers>
        </TextBox>
    </Grid>
</Window>





//cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp224
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    { 
        public MainWindow()
        {
            InitializeComponent(); 
            var vm = new MainVM();
            this.DataContext = vm;
        } 
    }

    public class MainVM
    {
        List<char> invalidCharsList { get; set; } = new List<char>();
        public MainVM()
        {
            invalidCharsList=new List<char>(System.IO.Path.GetInvalidFileNameChars());
        }

        public void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            var tbx = sender as TextBox;
            if (tbx != null && e!=null && !string.IsNullOrWhiteSpace(e.Text) && invalidCharsList!=null && invalidCharsList.Any())
            {
                if (e.Text.Any(x => invalidCharsList.Any(y => x == y)))
                {
                    MessageBox.Show($"Contains invalid chars:{e.Text}", "Contains invalid chars");
                    e.Handled = true; 
                }
                if (tbx.Text.Length > 10)
                {
                    MessageBox.Show("Max Length 10", "Max Length 10");
                    tbx.Text = tbx.Text.Substring(0, 10);
                    e.Handled = true;
                }
            }
        }

        public void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            var tbx = sender as TextBox;
            if (tbx != null && !string.IsNullOrWhiteSpace(tbx.Text) && invalidCharsList != null && invalidCharsList.Any())
            {
                if (tbx.Text.Any(x => invalidCharsList.Any(y => x == y)))
                {
                    MessageBox.Show("Contains invalid chars:{e.Text}", "Contains invalid chars");
                    e.Handled = true; 
                }
                if (tbx.Text.Length > 10)
                {
                    MessageBox.Show("Max Length 10", "Max Length 10");
                    tbx.Text = tbx.Text.Substring(0, 10);
                    e.Handled = true;
                }
            }
        }

    }
}

相關文章