我只想在 DataGridTextColumn 中允许正十进制值,如果用户输入 .369,系统将显示 0.369 怎么可能。我是 WPF 的新手
问问题
2700 次
2 回答
0
为此,您可能必须StringFormat
在 TextColumn 的Binding
.
尝试这个...
<Controls:DataGridTextColumn Header="Quantity"
Binding="{Binding Quantity,
StringFormat='{}{0:0.####}'}"/>
所以现在如果用户输入 .897 并按 enter,单元格值将显示为“0.897”。
于 2012-10-16T09:58:04.920 回答
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>
这是代码隐藏:
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;
}
}
}
于 2012-10-16T09:28:25.993 回答