If you want to restrict the type of input data for a particular column, you could try to refer to the code below.
MainWindow.xaml:
<Window.Resources>
<CollectionViewSource x:Key="CountryView" Source="{Binding Countries}"/>
</Window.Resources>
<Grid>
<DataGrid x:Name="dg" Width="200" Height="250" ItemsSource="{Binding Source={StaticResource CountryView}}"
SelectedItem="{Binding SelectedCountry}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="name" Binding="{Binding Country}"/>
<DataGridTemplateColumn Header="daten">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Daten}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding Daten}" PreviewKeyDown="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.Input;
namespace DataGridBindICollectionView
{
public partial class MainWindow : Window
{
ViewModel vm = new ViewModel();
public MainWindow()
{
InitializeComponent();
DataContext = vm;
}
private void TextBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key != Key.D0 && e.Key != Key.D1 && e.Key != Key.D2 && e.Key != Key.D3 && e.Key != Key.D4 && e.Key != Key.D5 && e.Key != Key.D6 && e.Key != Key.D7 && e.Key != Key.D8 && e.Key != Key.D9 && e.Key != Key.Back && e.Key != Key.NumPad0 && e.Key != Key.NumPad1 && e.Key != Key.NumPad2 && e.Key != Key.NumPad3 && e.Key != Key.NumPad4 && e.Key != Key.NumPad5 && e.Key != Key.NumPad6 && e.Key != Key.NumPad7 && e.Key != Key.NumPad8 && e.Key != Key.NumPad9 && e.Key != Key.Delete && e.Key != Key.Right && e.Key != Key.Left)
{
e.Handled = true;
}
if (e.Key == Key.Space || e.Key == Key.Back)
{
e.Handled = true;
}
}
}
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", Daten = DateTime.Now });
Countries.Add(new MyCountry() { Country = "NewYork", Daten = DateTime.Now });
Countries.Add(new MyCountry() { Country = "Shanghai", Daten = DateTime.Now });
}
}
public class MyCountry
{
public string Country { get; set; }
public DateTime Daten { get;set;}
}
}
The result:
You can only enter numbers, not characters.
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