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);
}
There are number of ways you can accomblish, this is one approach
xmlns:behaviours="http://schemas.microsoft.com/xaml/behaviors"
namespace to MechanicView.xaml.<TextBox Width="150">
<behaviours:Interaction.Triggers>
<behaviours:EventTrigger EventName="PreviewTextInput">
<behaviours:InvokeCommandAction Command="{Binding PreviewTextInputCommand}" PassEventArgsToCommand="True"/>
</behaviours:EventTrigger>
</behaviours:Interaction.Triggers>
</TextBox>
In MechanicViewModel.cs file, add ICommand PreviewTextInputCommand
variable
Implement PreviewTextInputCommand
variable as below
PreviewTextInputCommand = new RelayCommand<object>(PreviewTextInput, (o) => { return true; });
private void PreviewTextInput(object parameter)
{
var p = (parameter?.GetType().Name);
}