WPF Converter用法 利用coverter控制输入数字大小范围

发布时间 2023-07-05 00:00:30作者: 盛沧海

 

以下converter主要为控制数字的范围在指定的范围内:

 public class NumericRangeConverter : IValueConverter
    {
        public int MinValue { get; set; } 
        public int MaxValue { get; set; } 

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (int.TryParse(value?.ToString(), out int number))
            {
                number = Math.Max(number, MinValue);
                number = Math.Min(number, MaxValue);
                return number;
            }
            return null;
        }
    }

 

前端引入如下:

<Window x:Class="WpfApp.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:local="clr-namespace:WpfApp" 
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:MainViewModel/>
    </Window.DataContext>
    <Window.Resources>
        <local:NumericRangeConverter x:Key="nrc"/>
        <local:NumericRangeConverter x:Key="NumericRangeConverter" MinValue="0" MaxValue="100"/>
    </Window.Resources>
    <StackPanel Orientation="Vertical">
        <TextBox  Text="{Binding  Name,UpdateSourceTrigger=PropertyChanged, Converter={StaticResource NumericRangeConverter}}" />
    </StackPanel>
</Window>

注意上述代码中,将NumericRangeConverter引入了两次,但仅第2次指定了在Converter中申明的MinValue与MaxValue,如此在页面中可根据需要引入不同

key命名的资源,达到复用。

 

上述代码中涉及到的ViewModel如下:

public class MainViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler? PropertyChanged;
        public MainViewModel() { }

        private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged(nameof(Name));
            }
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

    }

 

在UI上运用时,若是textbox还可以用maxlength限制一下其字符长度;同时添加录入key值校验,其一般做法如下,通过其

PreviewTextInput事件来做,主要是因为设置 InputScope="Number" 往往是无效的。
        private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!char.IsDigit(e.Text[0]))
            {
                e.Handled = true; // 阻止输入
            }
        }