【问题标题】:WPF binding is very slow when conversion exceptions occur发生转换异常时 WPF 绑定很慢
【发布时间】:2018-05-28 00:49:26
【问题描述】:

我有一个文本框绑定到窗口上的双属性,UpdateSourceTrigger 设置为PropertyChanged。当文本框的内容不是有效数字时,键入文本会明显变慢。直接在 Visual Studio 外部运行可执行文件时速度会更快一些。奇怪的是,即使它们具有相似的规格,在我的办公机器上似乎要快得多。

是转换异常(我可以在输出窗口中看到记录)导致响应缓慢吗?我知道异常会减慢程序的速度,但肯定不会那么慢。我希望绑定代码在非常接近引发异常的位置捕获异常,因此堆栈不需要展开太多级别。我应该以某种方式阻止异常的发生吗? 如果是这样,我可以想到几种方法。

  1. 将文本框绑定到字符串属性
  2. 实现一个转换为“默认”值的自定义转换器,比如让我的属性为双倍?无法解析时设置为null。

有没有更好的办法?

这是一个显示我正在使用的绑定的最小示例。

<Window x:Class="WpfApp5.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp5"
        mc:Ignorable="d"
        x:Name="_window" Title="MainWindow" Height="176.351" Width="404.73">
    <Grid Margin="0,0,0,0">
        <TextBox HorizontalAlignment="Left" Height="22" Margin="10,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="73"
                 Text="{Binding Quantity, ElementName=_window, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, StringFormat='{}{0:#,0}'}"/>
    </Grid>
</Window>

public partial class MainWindow : Window
{
    public double Quantity { get; set; }

    public MainWindow()
    {
        InitializeComponent();
    }
}

【问题讨论】:

  • 首先绑定不能这样工作。除非您将 Quantity 声明为 DP 或通知属性更改。第二,我试过了,发生异常时它不会运行缓慢。请检查您的问题。
  • 但是,在我看来,如果适用的话,StringFormat 是最好的选择。
  • 您是否在附加调试器的情况下运行它?这可能会减慢速度,尤其是在抛出异常时。

标签: wpf data-binding


【解决方案1】:

这样的事情可能对你有用。

private double quantity;
public string Quantity
{
    get { return quantity.ToString(); } // , StringFormat='{}{0:#,0}'
    set
    {
        if(quantity.ToString() != value)
        {
            if (string.IsNullOrEmpty(value))
            {
                quantity = 0;
                NotifyPropertyChanged("Quantity");
            }
            else
            {
                double temp;
                if (double.TryParse(value, out temp))
                {
                    quantity = temp;
                    NotifyPropertyChanged("Quantity");
                }
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 2019-12-25
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多