这个问题的WPF解决方案是什么?

7

我曾使用WPF开发了两个中等规模的应用程序,WPF的简洁性和功能给我留下了深刻的印象。当我向一位业务应用程序员同事解释WPF的各种优点时,他提出了一个让我完全不知所措的问题:

问题:

他用以下方式在约2分钟内编写了一个应用程序:

  1. 打开新的WinForms项目。
  2. 定义一个名为Loan的类。
  3. 构建项目。
  4. 使用Loan定义一个对象数据源。
  5. 在“数据源资源管理器”中将Loan数据源的视图类型更改为“详细信息”。
  6. 在设计器中将数据源拖放到窗体上。
  7. 使用包含一个对象的Loan[]来提供数据源。
  8. 构建并运行应用程序。

代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WinForms_DataBinding_Example
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            loanBindingSource.DataSource = new Loan[] { new Loan() };
        }
    }

    public class Loan
    {
        public decimal Amount { get; set; }
        public decimal Rate { get; set; }
        public decimal Total { get { return Amount * Rate; } }
    }
}

设计师: enter image description here 应用程序: enter image description here 现在,每当您在窗口中更改AmountRate的值时,Total的值会相应地更改。设计师解释说,这是业务应用程序中非常有用的功能,在实体的一个属性发生任何更改时,立即更新视图,计算属性也会立即刷新,从而提高用户体验。考虑到典型的业务实体类具有许多属性,这样可以节省大量编码时间。然后他让我在WPF中做同样的事情。
我首先向他解释了我不明白这里进行了什么黑魔法。Total文本框如何自动更新?这是我的第一个问题:
Q1. Loan类没有实现INotifyPropertyChanged或类似的东西。那么,当AmountRate文本框失去焦点时,Total文本框如何更新?
然后我告诉他,我不知道如何在WPF中轻松完成同样的事情。但是,我在UI中使用了3个TextBlock和3个TextBox编写了相同的应用程序。我还需要让Loan类实现INotifyPropertyChanged。为AmountRate添加了备份字段。每当设置这些属性时,我都会为属性Total引发一次属性更改通知。最后,我得到了一个控件排列不好但与WinForms应用程序完成相同任务的应用程序。然而,这比WinForms方法要难得多。
我回家后想到了个好主意,将Loan数据源拖放到WPF窗口上(在将视图模式更改为详细信息后)。果然,我得到了与WinForms应用程序相同类型的UI,并在将数据源设置为与WinForms应用程序相同的Loan[]后,看起来已经完成。我运行了应用程序,更改了AmountRate字段,希望看到Total自动更改。但是,我很失望,Total字段没有更改: enter image description here 代码:
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.Navigation;
using System.Windows.Shapes;
using WinForms_DataBinding_Example;

namespace WPF_Grid_Example
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        {

            System.Windows.Data.CollectionViewSource loanViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("loanViewSource")));
            // Load data by setting the CollectionViewSource.Source property:
            loanViewSource.Source = new List<Loan>() { new Loan() };
        }
    }
}
<Window
        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:WinForms_DataBinding_Example="clr-namespace:WinForms_DataBinding_Example;assembly=WinForms_DataBinding_Example" mc:Ignorable="d" x:Class="WPF_Grid_Example.MainWindow"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded_1">
    <Window.Resources>
        <CollectionViewSource x:Key="loanViewSource" d:DesignSource="{d:DesignInstance {x:Type WinForms_DataBinding_Example:Loan}, CreateList=True}"/>
    </Window.Resources>
    <Grid>
        <Grid x:Name="grid1" DataContext="{StaticResource loanViewSource}" HorizontalAlignment="Left" Margin="121,123,0,0" VerticalAlignment="Top">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Label Content="Amount:" Grid.Column="0" HorizontalAlignment="Left" Margin="3" Grid.Row="0" VerticalAlignment="Center"/>
            <TextBox x:Name="amountTextBox" Grid.Column="1" HorizontalAlignment="Left" Height="23" Margin="3" Grid.Row="0" Text="{Binding Amount, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" VerticalAlignment="Center" Width="120"/>
            <Label Content="Rate:" Grid.Column="0" HorizontalAlignment="Left" Margin="3" Grid.Row="1" VerticalAlignment="Center"/>
            <TextBox x:Name="rateTextBox" Grid.Column="1" HorizontalAlignment="Left" Height="23" Margin="3" Grid.Row="1" Text="{Binding Rate, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" VerticalAlignment="Center" Width="120"/>
            <Label Content="Total:" Grid.Column="0" HorizontalAlignment="Left" Margin="3" Grid.Row="2" VerticalAlignment="Center"/>
            <TextBox x:Name="totalTextBox" Grid.Column="1" HorizontalAlignment="Left" Height="23" Margin="3" Grid.Row="2" Text="{Binding Total, Mode=OneWay}" VerticalAlignment="Center" Width="120"/>
        </Grid>

    </Grid>
</Window>

问题2:我之前曾被WinForms的黑魔法困扰过,现在同样的黑魔法在WPF中不起作用了,为什么?

问题3:如何使WPF版本自动更新Total字段,就像WinForms示例中那样?

问题4:对于这种类型的企业应用程序开发,哪个平台更好/更快?如果我要为WPF进行更好的辩论,我应该关注什么?

我希望我对问题有清晰的表述。如果需要任何澄清,请告诉我。谢谢。


3
哇,我印象深刻,WinForms可以自动生成一个带有三个文本框的屏幕……那又怎样?在WinForms中,其他任何事情都是不可能的,而WPF让您有能力定制EVERYTHING,并将ANYTHING绑定到ANYTHING,而不仅仅像WinForms中那样绑定Text属性。现实世界中的商业应用程序不仅仅是简单的文本框,它们需要比这更加复杂的逻辑,而WinForms需要大量的代码才能完成这些真正的应用程序,相对于简单的属性和XAML。 - Federico Berasategui
@HighCore:我相信你是对的。但是你的评论并没有回答我的任何问题。:( - nakiya
通常情况下,我觉得你正在基于特定用例比较两个框架。我认为这样做不会得出公正的结果。 - Ameen
只是为了明确:我只是举个例子。我的同事不是一个彻头彻尾的白痴,他不使用简单的WinForms。他至少使用一种知名的商业UI工具包来开发WinForms应用程序,如果我没记错的话,它们在这方面做得更好。我不想发起一场WPF与WinForms的圣战。我只是提出了四个具体的问题。 - nakiya
我不明白,在WPF版本中,您是通过定义带有自动属性但没有“INotifyPropertyChanged”的贷款类来开始的吗?我将尝试在VS2010中复制此操作,因为我认为VS 2012存在严重错误。 - Federico Berasategui
2个回答

6

问题1:如果您查看Windows窗体的设计文件,您会看到为您的3个文本框生成了大约300行代码。其中一些代码类似于:

this.amountTextBox.DataBindings.Add(
    new System.Windows.Forms.Binding("Text", 
        this.loanBindingSource, "Amount", true));

Binding和BindingSource一起协作更新绑定的值,并在每次一个值改变时导致所有绑定的控件被更新(使用反射)。

Q2: 因为WPF设计器不创建.Designer.cs文件和相关代码的混乱。你需要显式实现INotifyPropertyChange,可以通过使用MVVM Light的ViewModelBase来简化,例如:

public class Loan : ViewModelBase
{
    public decimal Amount
    {
        get
        {
            return this.amount;
        }
        set
        {
            if (Set(() => Amount, ref this.amount, value))
            {
                RaisePropertyChanged(() => Total);
            }
        }
    }

问题三: 1)当金额或利率发生变化时,除了对该属性进行属性更改通知外,还应为计算属性“总计”提供属性更改通知。 2)修改您在金额和利率上的绑定为Binding="{Binding Amount, UpdateSourceTrigger=LostFocus}"

问题四:在我看来,WPF无疑是更可测试、可维护和易于理解的方式。


1

Q4的答案:

尽管winforms有能力为类生成3个愚蠢的文本框,但WPF是一个更好、可伸缩和强大的框架。它具有更高的性能,因为它具有硬件加速等功能,并且需要更少或没有代码来完成一些在winforms中需要大量代码的任务,比如this,或者这个:

<CheckBox x:Name="chk"/>
<TextBox IsEnabled="{Binding IsChecked,ElementName=chk}"/>

此外,典型的业务应用程序必须处理数千或数十万条记录,UI虚拟化可以产生巨大的影响。总的来说,WinForms虽然具有一些设计师好处(这更是Visual Studio而不是WinForms本身的特点),但在涉及业务线时远远不如实用和适当。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接