Search code examples
c#wpf

Assigns a function to PreviewTextInput in the Texbox preserving the WPF pattern


I have a window named MechanicView.xaml and its back-end that is MechanicView.xaml.cs. The MechanicView.xaml window is connected via DataContext to the MechanicViewModel.cs file. The MechanicView.xaml window contains a TextBox with a PreviewTextInput event. How do I assign a function to the PreviewTextInput event that will be in the MechanicViewModel.cs file? I want to keep the MVVM pattern so I want to avoid creating a function in the MechanicView.xaml.cs file

My actually code in MechanicView.xaml

<TextBox Text="{Binding StartNumber, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" PreviewTextInput="TextBox_PreviewTextInput" FontSize="16" Height="27" Margin="10" >

My actually code in MechanicView.xaml.cs

private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) 
{
   Regex regex = new Regex("[^0-9]+"); 
   e.Handled = regex.IsMatch(e.Text); 
}

Solution

  • There are number of ways you can accomblish, this is one approach

    1. Download Microsoft.Xaml.Behaviors.Wpf nuget package to your project.
    2. Add xmlns:behaviours="http://schemas.microsoft.com/xaml/behaviors" namespace to MechanicView.xaml.
    3. Add this code in MechanicView.xaml (not tested)
    <TextBox Width="150">
       <behaviours:Interaction.Triggers>
           <behaviours:EventTrigger EventName="PreviewTextInput">
               <behaviours:InvokeCommandAction Command="{Binding PreviewTextInputCommand}" PassEventArgsToCommand="True"/>
           </behaviours:EventTrigger>
        </behaviours:Interaction.Triggers>
    </TextBox>
    
    1. In MechanicViewModel.cs file, add ICommand PreviewTextInputCommand variable

    2. Implement PreviewTextInputCommand variable as below

        PreviewTextInputCommand = new RelayCommand<object>(PreviewTextInput, (o) => { return true; });
    
    1. The command method will look as below
        private void PreviewTextInput(object parameter)
        {
            var p = (parameter?.GetType().Name);
        }