我想在DataGridTextColumn中仅允许正十进制值,如果用户输入.369,系统将显示0.369如何可能。我是WPF的新手
答案 0 :(得分:0)
试试这个
XAML:
<Window x:Class="SandBox.Window4"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SandBox"
Title="Window4" Height="300" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<DataGrid x:Name="dg" Grid.Row="0" >
<DataGrid.Columns>
<DataGridTemplateColumn Header="Quantity" Width="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Qty, Mode=TwoWay}" x:Name="tb" TextChanged="tb_TextChanged">
</TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
这是CodeBehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
namespace SandBox
{
/// <summary>
/// Interaction logic for Window4.xaml
/// </summary>
public partial class Window4 : Window
{
public ObservableCollection<ItemClass> Collection = new ObservableCollection<ItemClass>();
public Window4()
{
InitializeComponent();
//Collection.Add(new ItemClass("123"));
//Collection.Add(new ItemClass("456"));
Collection.Add(new ItemClass("123"));
Collection.Add(new ItemClass("456"));
dg.ItemsSource = Collection;
}
private void tb_TextChanged(object sender, TextChangedEventArgs e)
{
int result = 0;
TextBox txt = sender as TextBox;
if (txt != null)
{
if (!int.TryParse(txt.Text, out result))
{
if(result >= 0)
{
txt.Text = txt.Text.Substring(0, txt.Text.Length - 1);
txt.CaretIndex = txt.Text.Length;
}
}
}
}
}
public class ItemClass
{
public string Qty { get; set; }
public ItemClass(string qty)
{
Qty = qty;
}
}
}
答案 1 :(得分:0)
为此,您可能需要在TextColumn的StringFormat
中设置适当的Binding
。
试试这个......
<Controls:DataGridTextColumn Header="Quantity"
Binding="{Binding Quantity,
StringFormat='{}{0:0.####}'}"/>
现在如果用户输入.897并按Enter ,则单元格值将显示为“0.897”。