WPF Converter用法 利用coverter控制输入数字大小范围
以下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; // 阻止输入 } }
*****有道无术,术尚可求;有术无道,止于术。*****
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现