【发布时间】:2015-11-23 15:43:12
【问题描述】:
我编写了一个非常简单的 WPF 应用程序。 我正在尝试使用自定义字符串格式将双属性绑定到文本框文本。这是视图模型的代码和窗口的代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace StringFormat
{
internal class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
DoubleProperty = 0;
}
private double _doubleProperty;
public double DoubleProperty
{
get { return _doubleProperty; }
set
{
_doubleProperty = value;
NotifyPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
<Window x:Class="StringFormat.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converters="clr-namespace:StringFormat"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBox Grid.Row="0"
Grid.Column="0"
Width="120"
Height="25"
TextAlignment="Center"
Text="{Binding DoubleProperty, StringFormat={}{##.##}, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</Window>
namespace StringFormat
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
}
}
当我运行应用程序时,它可以工作,但我在控制台中收到以下错误:
System.Windows.Data 错误:6:“StringFormat”转换器无法转换值“0”(类型“Double”);如果可用,将使用后备值。绑定表达式:路径=双属性; DataItem='ViewModel' (HashCode=486165);目标元素是'TextBox'(名称='');目标属性是“文本”(类型“字符串”) FormatException:“System.FormatException:输入字符串的格式不正确。 在 System.Text.StringBuilder.AppendFormat(IFormatProvider 提供程序,字符串格式,对象 [] 参数) 在 System.String.Format(IFormatProvider 提供程序,字符串格式,对象 [] 参数) 在 System.Windows.Data.BindingExpression.ConvertHelper(IValueConverter 转换器,对象值,类型 targetType,对象参数,CultureInfo 文化)'
我尝试更改字符串格式,但没有出现错误,但我认为当您尝试删除文本框的内容时出现“0.0”有点烦人。
我不知道该怎么做才能解决错误,但也可以在没有“0.0”的情况下删除文本框文本。 你能给我一些建议如何处理这种情况吗? 谢谢!
【问题讨论】:
标签: wpf textbox string-formatting