c# – 将TextBox绑定到Nullable Double?

前端之家收集整理的这篇文章主要介绍了c# – 将TextBox绑定到Nullable Double?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想绑定一个Double?到TextBox,我遇到了问题,因为当用户清空文本框时,会发生验证.
我认为我的应用程序在我找不到的某个地方进行了验证,所以我创建了一个快速应用程序来测试.
  1. public partial class MainWindow : Window
  2. {
  3. public MainWindow()
  4. {
  5. InitializeComponent();
  6. DataContext = new viewmodel() {Value = 3,Value2 = null};
  7. }
  8. }
  9.  
  10. public class viewmodel
  11. {
  12. public double Value { get; set; }
  13. public double? Value2 { get; set; }
  14. }

xaml

  1. <StackPanel Grid.Row="0" Orientation="Horizontal" Margin="5" Height="20px">
  2. <TextBlock Margin="0,5,0">Double:</TextBlock>
  3. <TextBox Width="50px" Text="{Binding Value}"></TextBox>
  4. </StackPanel>
  5. <StackPanel Grid.Row="1" Orientation="Horizontal" Margin="5" Height="20px">
  6. <TextBlock Margin="0,0">Double?:</TextBlock>
  7. <TextBox Width="50px" Text="{Binding Value2}"></TextBox>
  8. </StackPanel>

当我运行应用程序时绑定到Value2的TextBox为空,但如果我键入一个值然后删除它,当TextBox失去焦点时它会显示错误.它只会在我键入值时消失.

我发现this post建议使用一个字符串,但他最初使用的是双倍而不是双倍?

我怎样才能做到这一点?是使用字符串的唯一方法吗?

绑定到双倍似乎很奇怪?不允许我设置空值.

解决方法

首先.

不是这个:

  1. <TextBox Width="50px"

但是这个:

  1. <TextBox Width="50"

第二:如果你这样做,你的情况应该解决

代替 :

  1. <TextBox Width="50px" Text="{Binding Value2}"></TextBox>

做:

  1. <TextBox Width="50" Text="{Binding Value2,TargetNullValue=''}"></TextBox>

希望有所帮助

猜你在找的C#相关文章