How to enter or bind data from another field to the selected DataGridCell in the PreviewKeyDown event?

رضا جافری 1,296 Reputation points
2022-05-03T22:36:39.467+00:00

Hi
I use the following method to set the TextBox date limit.
XAML (MaxLength):

<TextBox x:Name="LoanDate_TextBox" PreviewKeyDown="LoanDate_TextBox_PreviewKeyDown" GotFocus="LoanDate_TextBox_GotFocus" LostFocus="LoanDate_TextBox_LostFocus" Padding="4,4,0,0" Template="{StaticResource TextBoxControlTemplate}" HorizontalAlignment="Left" Height="30" MaxLength="10" TextWrapping="Wrap" VerticalAlignment="Top" Width="178" Margin="0,51,0,0"/>  

C#:

    private void LoanDate_TextBox_PreviewKeyDown(object sender, KeyEventArgs e)  
    {  
        switch (!((e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Back || e.Key == Key.Home || e.Key == Key.End || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Tab || Keyboard.Modifiers == ModifierKeys.Control))  
        {  
            case true:  
                e.Handled = true;  
                break;  
            default:  
                switch (e.Key == Key.A || e.Key == Key.C || e.Key == Key.V || e.Key == Key.Y || e.Key == Key.Z)  
                {  
                    case true:  
                        break;  
                }  
                switch (e.Key != Key.Back && e.Key != Key.Home && e.Key != Key.End && e.Key != Key.Left && e.Key != Key.Right)  
                {  
                    case true:  
                        byte j = 0;  
                        for (byte i = 0; i < LoanDate_TextBox.Text.Length; i++)  
                        {  
                            switch (LoanDate_TextBox.Text[i] == '/')  
                            {  
                                case true:  
                                    j++;  
                                    break;  
                            }  
                        }  
                        switch (j < 2)  
                        {  
                            case true:  
                                switch (LoanDate_TextBox.Text.Length)  
                                {  
                                    case 2:  
                                        LoanDate_TextBox.Text = '/' + LoanDate_TextBox.Text;  
                                        break;  
                                    case 5:  
                                        LoanDate_TextBox.Text = '/' + LoanDate_TextBox.Text;  
                                        break;  
                                }  
                                break;  
                        }  
                        break;  
                    default:  
                        switch (e.Key)  
                        {  
                            case Key.Back:  
                                switch (App.EnumLanguage)  
                                {  
                                    case AllLanguage.Persian:  
                                        switch (LoanDate_TextBox.Text.Length)  
                                        {  
                                            case 3:  
                                                LoanDate_TextBox.SelectionStart = 3;  
                                                break;  
                                            case 6:  
                                                LoanDate_TextBox.SelectionStart = 6;  
                                                break;  
                                        }  
                                        break;  
                                }  
                                break;  
                        }  
                        break;  
                }  
                break;  
        }  
    }  

As you can see it works fine (I just enter numbers):
198661-textbox.gif
So I tried to use this method in the DataGridCell PreviewKeyDown event.
XAML:

<DataGridTextColumn x:Name="DateTaken" Binding="{Binding DateTaken}" Width="SizeToHeader">  
  <DataGridTextColumn.CellStyle>  
    <Style TargetType="DataGridCell">  
       <EventSetter Event="PreviewKeyDown" Handler="DateTaken_PreviewKeyDown"/>  
    </Style>  
  </DataGridTextColumn.CellStyle>  
</DataGridTextColumn>  

C#:

    TextBox DataGridTextColumnValue = new TextBox();  
    public string InputTextFilter(string Input)  
    {  
        StringBuilder FilteredString = new StringBuilder();  
        for (byte i = 0; i < Input.Length; i++)  
        {  
            switch (char.IsDigit(Input[i]) || Input[i] == '/')  
            {  
                case true:  
                    FilteredString.Append(Input[i]);  
                    break;  
            }  
        }  
        return FilteredString.ToString();  
    }  
    private void DateTaken_PreviewKeyDown(object sender, KeyEventArgs e)  
    {  
        switch (!((e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Back || e.Key == Key.Home || e.Key == Key.End || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Tab || Keyboard.Modifiers == ModifierKeys.Control))  
        {  
            case true:  
                e.Handled = true;  
                break;  
            default:  
                DataRowView DV = (DataRowView)BookDataGrid.SelectedItem;  
                DataGridTextColumnValue.Text = InputTextFilter(BookDataGrid.CurrentCell.Column.GetCellContent(DV).ToString());  
                switch (e.Key == Key.A || e.Key == Key.C || e.Key == Key.V || e.Key == Key.Y || e.Key == Key.Z)  
                {  
                    case true:  
                        break;  
                }  
                switch (e.Key != Key.Back && e.Key != Key.Home && e.Key != Key.End && e.Key != Key.Left && e.Key != Key.Right)  
                {  
                    case true:  
                        byte j = 0;  
                        for (byte i = 0; i < DataGridTextColumnValue.Text.Length; i++)  
                        {  
                            switch (DataGridTextColumnValue.Text[i] == '/')  
                            {  
                                case true:  
                                    j++;  
                                    break;  
                            }  
                        }  
                        switch (j < 2)  
                        {  
                            case true:  
                                switch (DataGridTextColumnValue.Text.Length)  
                                {  
                                    case 2:  
                                        DataGridTextColumnValue.Text = '/' + DataGridTextColumnValue.Text;  
                                        break;  
                                    case 5:  
                                        DataGridTextColumnValue.Text = '/' + DataGridTextColumnValue.Text;  
                                        break;  
                                }  
                                break;  
                        }  
                        break;  
                    default:  
                        switch (e.Key)  
                        {  
                            case Key.Back:  
                                switch (App.EnumLanguage)  
                                {  
                                    case AllLanguage.Persian:  
                                        switch (DataGridTextColumnValue.Text.Length)  
                                        {  
                                            case 3:  
                                                DataGridTextColumnValue.SelectionStart = 3;  
                                                break;  
                                            case 6:  
                                                DataGridTextColumnValue.SelectionStart = 6;  
                                                break;  
                                        }  
                                        break;  
                                }  
                                break;  
                        }  
                        break;  
                }  
                break;  
        }  
    }  

Now my question is how to bind the DataGridTextColumnValue text to the selected DataGridCell (lines 50 and 53) ?

Thanks for your attention. I’m looking forward to your reply.

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,709 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,603 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
789 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Hui Liu-MSFT 47,256 Reputation points Microsoft Vendor
    2022-05-04T07:25:45.313+00:00

    I tried DateTaken_PreviewKeyDown and LoanDate_TextBox_PreviewKeyDown in the EventSetter of CellStyle , without success. You could try by binding the TextBox with the PreviewKeyDown event to the DataGridTemplateCloumn. I commented the relevant code for App.EnumLanguage because I don't know its definition.
    MainWindow.xaml:

     <Window.Resources>  
            <CollectionViewSource x:Key="CountryView" Source="{Binding Countries}"/>  
        </Window.Resources>  
        <Grid>  
            <DataGrid x:Name="BookDataGrid" Width="400" Height="250" ItemsSource="{Binding Source={StaticResource CountryView}}"   
                       SelectedItem="{Binding SelectedCountry}"  AutoGenerateColumns="False">  
                <DataGrid.Columns>  
                    <DataGridTextColumn Header="name" Binding="{Binding Country}"/>  
    
                    <DataGridTemplateColumn Header="daten"  Width="100" >  
    
                        <DataGridTemplateColumn.CellTemplate>  
                            <DataTemplate>  
                                <TextBlock Text="{Binding DateTaken}"/>  
                            </DataTemplate>  
                        </DataGridTemplateColumn.CellTemplate>  
                        <DataGridTemplateColumn.CellEditingTemplate >  
                            <DataTemplate>  
                                <TextBox x:Name="DataGridTextColumnValue" Text="{Binding  DateTaken}" PreviewKeyDown="LoanDate_TextBox_PreviewKeyDown"/>  
    
                            </DataTemplate>  
                        </DataGridTemplateColumn.CellEditingTemplate>  
                    </DataGridTemplateColumn>  
                </DataGrid.Columns>  
    
            </DataGrid>  
        </Grid>  
    

    MainWindow.xaml.cs:

    using System;  
    using System.Collections.ObjectModel;  
    using System.Windows;  
    using System.Windows.Controls;  
    using System.Windows.Input;  
    
    namespace PreviewKeyDownDataGridCell  
    {  
      public partial class MainWindow : Window  
      {  
        ViewModel vm = new ViewModel();  
        public MainWindow()  
        {  
          InitializeComponent();  
          DataContext = vm;  
        }  
    
            private void LoanDate_TextBox_PreviewKeyDown(object sender, KeyEventArgs e)  
            {  
    
                var LoanDate_TextBox  = sender as TextBox;  
                switch (!((e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Back || e.Key == Key.Home || e.Key == Key.End || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Tab || Keyboard.Modifiers == ModifierKeys.Control))  
                {  
                    case true:  
                        e.Handled = true;  
                        break;  
                    default:  
                        switch (e.Key == Key.A || e.Key == Key.C || e.Key == Key.V || e.Key == Key.Y || e.Key == Key.Z)  
                        {  
                            case true:  
                                break;  
                        }  
                        switch (e.Key != Key.Back && e.Key != Key.Home && e.Key != Key.End && e.Key != Key.Left && e.Key != Key.Right)  
                        {  
                            case true:  
                                byte j = 0;  
                                for (byte i = 0; i < LoanDate_TextBox.Text.Length; i++)  
                                {  
                                    switch (LoanDate_TextBox.Text[i] == '/')  
                                    {  
                                        case true:  
                                            j++;  
                                            break;  
                                    }  
                                }  
                                switch (j < 2)  
                                {  
                                    case true:  
                                        switch (LoanDate_TextBox.Text.Length)  
                                        {  
                                            case 2:  
                                                LoanDate_TextBox.Text = '/' + LoanDate_TextBox.Text;  
                                                break;  
                                            case 5:  
                                                LoanDate_TextBox.Text = '/' + LoanDate_TextBox.Text;  
                                                break;  
                                        }  
                                        break;  
                                }  
                                break;  
                            default:  
                                //switch (e.Key)  
                                //{  
                                //    case Key.Back:  
                                //        switch (App.EnumLanguage)  
                                //        {  
                                //            case AllLanguage.Persian:  
                                //                switch (LoanDate_TextBox.Text.Length)  
                                //                {  
                                //                    case 3:  
                                //                        LoanDate_TextBox.SelectionStart = 3;  
                                //                        break;  
                                //                    case 6:  
                                //                        LoanDate_TextBox.SelectionStart = 6;  
                                //                        break;  
                                //                }  
                                //                break;  
                                //        }  
                                //        break;  
                                //}  
                                break;  
                        }  
                        break;  
                }  
            }  
      }  
      public class ViewModel  
      {  
        public ObservableCollection<MyCountry> Countries { get; set; }  
        public MyCountry SelectedCountry { get; set; }  
        public ViewModel()  
        {  
          Countries = new ObservableCollection<MyCountry>();  
          Countries.Add(new MyCountry() { Country = "Beijing", DateTaken = DateTime.Now });  
          Countries.Add(new MyCountry() { Country = "NewYork", DateTaken = DateTime.Now });  
          Countries.Add(new MyCountry() { Country = "Shanghai", DateTaken = DateTime.Now });  
        }  
      }  
      public class MyCountry  
      {  
        public string Country { get; set; }  
        public DateTime DateTaken { get; set; }  
      }  
    }  
    

    The result:
    198763-1.gif


    If the response is helpful, please click "Accept Answer" and upvote it.
     Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread. 

    [5]: https://learn.microsoft.com/en-us/answers/articles/67444/email-notifications.html