【问题标题】:custom string format text input wpf自定义字符串格式文本输入wpf
【发布时间】:2019-02-21 12:02:40
【问题描述】:

我的值采用 [double-type-value][unit] 格式,其中单位可以是“g”或“mg”(g 表示克,mg 表示毫克)。有没有办法允许用户仅以该格式在 TextBox 中输入文本。例如,像只接受数字的迷你文本框和迷你组合框,其中在普通文本框中的值为“g”或“mg”或其他什么?在文本框中输入内容之前,单位的默认值为“g”会很好,这样如果有更多文本框,用户就不必在文本框末尾输入 g 或 mg。

编辑 我使用的是 MVVM 模式,所以后面的代码违反了它。

【问题讨论】:

  • 你可以使用转换器
  • @DenisSchaf 如果您的意思是实现一个继承 IValueConverter 的类,它只会将用户键入的有效值转换为我需要的格式。我想阻止用户输入除该格式的值之外的任何其他内容。
  • 在这种情况下,您只有一种可能性,即在此事件中使用 PreviewTextInput 事件,如果转换失败处理输入事件,则将输入文本转换为双精度值,因此如果转换成功只需退出您的功能。为此目的创建自定义控件是明智的,因此您可以在需要时轻松重用它
  • 单位量词是否与代码相关?我的意思是,您如何编写代码知道给定值是以 mg 还是 g 为单位并相应地乘/除该值(或者这完全不相关)。
  • @LittleBit 我有一个数据库,数据库中的所有内容都以克记录。我只使用转换 i UI 来获得更好的用户体验。比如用户想输入0.01mg,我不想他每次都写0.00001。

标签: c# wpf string-formatting


【解决方案1】:

您实际上应该处理三个​​事件:

  • PreviewTextInput
  • PreviewKeyDown - 防止输入空白字符,因为它们不是由 PreviewTextInput 处理的
  • DataObject.Pasting 附加事件以防止用户从剪贴板粘贴无效文本

最好将此逻辑封装在行为中。 A 有类似行为的示例:TextBoxIntegerInputBehavior、TextBoxDoubleInputBehavior。

【讨论】:

    【解决方案2】:

    由于这个输入的性质,我建议你创建一个小CustomControl,更具体的是一个TextBox,它能够限制Input并将Text转换为相应的值->一个@987654325 @。

    GramTextBox 有一个称为Gram 的Gram,它表示输入的Text 的值,并且可以绑定到ViewModel(注意:由于GramTextBox,绑定必须包含Mode=TwoWay尝试更新绑定的Source)。

    代码

    public sealed class GramTextBox : TextBox
    {
        //Constructor
        public GramTextBox() : base()
        {
            Text = "0g"; //Initial value
            TextChanged += OnTextChanged;
            DataObject.AddPastingHandler(this, OnPaste);
        }
    
        //Style override (get the Style of a TextBox for the GramTextBox)
        static GramTextBox()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(GramTextBox), new FrameworkPropertyMetadata(typeof(TextBox)));
        }
    
        //Define a DependencyProperty to make it bindable (dont forget 'Mode=TwoWay' due the bound value is updated from this GramTextBox)
        [Category("Common"), Description("Converted double value from the entered Text in gram")]
        [Browsable(true)]
        [Bindable(true)]
        public double Gram
        {
            get { return (double)GetValue(PathDataProperty); }
            set { SetCurrentValue(PathDataProperty, value); }
        }
        public static DependencyProperty PathDataProperty = DependencyProperty.Register("Gram", typeof(double), typeof(GramTextBox), new PropertyMetadata(0d));
    
        //Extract the Gram value when Text has changed
        private void OnTextChanged(object sender, TextChangedEventArgs e)
        {
            ExtractGram(Text);
        }
    
        //Suppress space input
        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            e.Handled = e.Key == Key.Space;
        }
    
        //Check text inputs
        protected override void OnPreviewTextInput(TextCompositionEventArgs e)
        {
            e.Handled = !IsValidText(Text.Insert(CaretIndex, e.Text));
        }
    
        //check paste inputs
        private void OnPaste(object sender, DataObjectPastingEventArgs e)
        {
            //Check if pasted object is string
            if(e.SourceDataObject.GetData(typeof(string)) is string text)
            {
                //Check if combined string is valid
               if(!IsValidText(Text.Insert(CaretIndex, text))) { e.CancelCommand(); }
            }
            else { e.CancelCommand(); }
        }
    
        //Check valid format for extraction (supports incomplete inputs like 0.m -> 0g)
        private bool IsValidText(string text)
        {
            return Regex.IsMatch(text, @"^([0-9]*?\.?[0-9]*?m?g?)$");
        }
    
        //Extract value from entered string
        private void ExtractGram(string text)
        {
            //trim all unwanted characters (only allow 0-9 dots and m or g)
            text = Regex.Replace(text, @"[^0-9\.mg]", String.Empty);
            //Expected Format -> random numbers, dots and couple m/g
    
            //trim all text after the letter g 
            text = text.Split('g')[0];
            //Expected Format -> random numbers, dots and m
    
            //trim double dots (only one dot is allowed)
            text = Regex.Replace(text, @"(?<=\..*)(\.)", String.Empty);
            //Expected Format -> random numbers with one or more dots and m
    
            //Check if m is at the end of the string to indicate milli (g was trimmed earlier)
            bool isMilli = text.EndsWith("m");
    
            //Remove all m, then only a double number should remain
            text = text.Replace("m", String.Empty);
            //Expected Format -> random numbers with possible dot
    
            //trim all leading zeros
            text = text.TrimStart(new char[] { '0' });
            //Expected Format -> random numbers with possible dot
    
            //Check if dot is at the beginning
            if (text.StartsWith(".")) { text = $"0{text}"; }
            //Expected Format -> random numbers with possible dot
    
            //Check if dot is at the end
            if (text.EndsWith(".")) { text = $"{text}0"; }
            //Expected Format -> random numbers with possible dot
    
            //Try to convert the remaining String to a Number, if it fails -> 0
            Double.TryParse(text, out double result);
    
            //Update Gram Property (divide when necessary)
            Gram = (isMilli) ? result / 1000d : result;
        }
    }
    

    用法

    将此Class 放入YOURNAMESPACE 并在XAML 添加命名空间别名

    xmlns:cc="clr-namespace:YOURNAMESPACE"
    

    现在GramTextBox可以这样使用

    <cc:GramTextBox Gram="{Binding VMDoubleProperty, Mode=TwoWay}" ... />
    

    每当GramTextBox 中的Text 发生变化(例如,来自键盘/粘贴等的有效输入)时,它都会更新ViewModel 中的绑定Property。

    备注

    旨在将.00g、0.0m、.mg 等无意义的输入设置为Gram Property 至0(如备用值)。

    个人笔记

    感谢@Pavel 提供PasteHandler

    编辑

    要在DataGrid 中使用此GramTextBox,您可以覆盖Column 的CellTemplate:

    <DataGrid AutoGenerateColumns="False" ... >
        <DataGrid.Columns>
           <!-- Put some other Columns here like DataGridTextColumn -->
           <DataGridTemplateColumn Header="Mass">
               <DataGridTemplateColumn.CellTemplate>
                   <DataTemplate>
                       <cc:GramTextBox Gram="{Binding VMDoubleProperty, Mode=TwoWay}" ... />
                   </DataTemplate>
               </DataGridTemplateColumn.CellTemplate>
           </DataGridTemplateColumn>
           <!-- Put some other Columns here -->
       </DataGrid.Columns>
    </DataGrid> 
    

    【讨论】:

    • 我可以对数据网格使用类似的方法吗?因为有些情况是用户在datagrid中写入数据?
    • @TatjanaCerovic 当然可以,但是您必须将其设置为DataGrid 的CellTemplate,并且可以手动定义另一个Columns。详情见编辑。
    【解决方案3】:

    您可以在TextBox 上使用带有事件PreviewTextInput、DataObject.Pasting 和PreviewKeyDown 的正则表达式来检查新字符串是否与regex 匹配,如果不匹配,您可以取消操作。

    像这样:

    xaml:

    ...
    <TextBox PreviewTextInput="txtbox_PreviewTextInput" DataObject.Pasting="txtbox_Pasting" PreviewKeyDown="txtbox_PreviewKeyDown" />
    ...
    

    后面的代码:

    public partial class MainWindow : Window
    {
        private Regex gramOrMilliGramRegex = new Regex("^[0-9.-]+(m?g)?$");
    
        public MainWindow ()
        {
            InitializeComponent();
        }
    
        private void txtbox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if(sender is TextBox txtbox)
            {
                string newString = txtbox.Text.Substring(0, txtbox.CaretIndex) + e.Text + txtbox.Text.Substring(txtbox.CaretIndex); //Build the new string
                e.Handled = !gramOrMilliGramRegex.IsMatch(e.Text); //Check if it matches the regex
            }
    
        }
    
        private void txtbox_Pasting(object sender, DataObjectPastingEventArgs e)
        {
            if(sender is TextBox txtbox)
            {
                string newString = txtbox.Text.Substring(0, txtbox.CaretIndex) + e.DataObject.GetData(typeof(string)) as string + txtbox.Text.Substring(txtbox.CaretIndex); //Build new string
                if (!digitOnlyRegex.IsMatch(newString)) //Check if it matches the regex
                {
                    e.CancelCommand();
                }
            }
    
        private void txtbox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            //Prevents whitespace
            if (e.Key == Key.Space)
            {
                e.Handled = true;
            }
            base.OnPreviewKeyDown(e);
        }
    }
    


    更新:正如您现在提到的,您正在使用 MVVM 并且不想违反该模式。

    您需要将这些事件路由到您的ViewModel 中的命令,并将事件放在上面。

    您可以在 xaml 中的 TextBox 中使用此代码:

    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:cmd ="http://www.galasoft.ch/mvvmlight"
    
    ...
    
    <TextBox>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="PreviewTextInput">
                <cmd:EventToCommand Command="{Binding Mode=OneWay, Path=PreviewTextInputCommand}" PassEventArgsToCommand="True" />
            </i:EventTrigger>
            <i:EventTrigger EventName="DataObject.Pasting">
                <cmd:EventToCommand Command="{Binding Mode=OneWay, Path=DataObject_PastingCommand}" PassEventArgsToCommand="True" />
            </i:EventTrigger>
            <i:EventTrigger EventName="PreviewKeyDown">
                <cmd:EventToCommand Command="{Binding Mode=OneWay, Path=PreviewKeyDownCommand}" PassEventArgsToCommand="True" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </TextBox>
    

    【讨论】:

    • 这违反了 MVVM 模式,我说我在 cmets 中使用它。我现在编辑了帖子
    • @TatjanaCerovic 已更新,因此可以在不违反 MVVM 模式的情况下实施。
    • @Alfie Routing 命令将您的 gui 修改为您的 ViewModel 仍然会违反 MVVM 模式,即使后面的代码保持为空...
    • @TatjanaCerovic 老实说,我认为原始解决方案在 MVVM 方面完全没问题,它的视图工作是处理用户输入并与视图模型交互,因此验证用户输入是视图的责任并且不会破坏 MVVM 模式。这有点武断,不过这里没有错误或正确的答案,我不想开始辩论,只是我的看法。
    【解决方案4】:

    为了防止用户输入除数字以外的任何内容,您必须使用 PrevieTextInput 事件,为此创建自定义控件是有意义的。下面的几行将阻止用户输入除数字以外的任何内容

        <Grid>            
            <TextBox Text="{Binding Text}" PreviewTextInput="TextBox_PreviewTextInput"/>
            <TextBlock HorizontalAlignment="Right" Margin="5,0">g</TextBlock>
        </Grid>
    
    
        private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            var tb = sender as TextBox;
            e.Handled = !double.TryParse(tb.Text+e.Text, out double d);
        }
    

    附:如果你不喜欢使用 try Catch,你可以使用正则表达式

    【讨论】:

    • 如果我理解正确的话,她应该使用正则表达式,因为她想允许像“105g”或“11mg”这样的字符串。
    • 我认为她不想在实际字符串中添加一个“g”,这会使进一步的处理变得非常困难,我猜她想显示它的克或毫克。这可以通过覆盖文本块轻松实现(编辑我的答案)
    • 这是否违反了 MVVM 模式,因为我正在使用它?
    • 如果您编写一个只允许特定输入的控件/模板,它确实不违反 MVVM。事实上,您可以将其实现为行为文本框。
    • 另外,我建议您仔细查看使用过的Event。例如,当您将某些内容粘贴到 TextBox 中时,PreviewTextInput 不会防止格式错误的 strings。当有特定的转换方法时,请不要使用Try/catch 模式检查某些内容 -> Double.TryParse()。
    猜你喜欢
    • 2012-08-28
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多