前言:
WPF数据绑定对于WPF应用程序来说尤为重要,本文将讲述使用MVVM模式进行数据绑定的四步走用法:
具体实例代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public class NotifyPropertyObject : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChanged( string propertyName) { if (PropertyChanged != null ) { PropertyChanged.Invoke( this , new PropertyChangedEventArgs(propertyName)); } } } private MainWindowVM vm = new MainWindowVM(); //重点 public MainWindow() { InitializeComponent(); this .DataContext = vm; //重点 } |
第二步:为每一个界面建立其模型类,如MainWindowVM,AzimuthWindowVM........,此种类型的类同样需继承自类NotifyPropertyObject
注意:(1)此类中主要添加后台的实现代码,其一是使后台代码尽可能简单;其二是便于数据的绑定
(2)此类中大多数情况下写的是属性和方法
示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
public class MainWindowVM : NotifyPropertyObject { private double _dmsL0; //中央子午线经度 public double dmsL0 { get { return _dmsL0; } set { _dmsL0 = value; RaisePropertyChanged( "dmsL0" ); } } } public class AzimuthWindowVM : NotifyPropertyObject { private string azName = "A001->B004的坐标方位角" ; public string AzName { get { return azName; } set { azName = value; RaisePropertyChanged( "AzName" ); } } } |
第三步:如果类中存在与界面相关的量,则让该类继承类NotifyPropertyObject,并在派生类中在属性中的Set代码块中进行绑定
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public class Ellipsoid : NotifyPropertyObject { private double _a; //长半轴 public double a { get => _a; set { _a = value; if (_a > 0 && _f > 0) { Init(a, f); } RaisePropertyChanged( "a" ); } } } |
第四步:在界面设计代码中进行绑定
示例:
1
2
3
4
|
1、<TextBox Grid.Column= "2" VerticalAlignment= "Center" Text= "{Binding CurrentEllipsoid.a}" IsEnabled= "{Binding CurrentEllipsoid.IsCustomEllopsoid}" /> 2、<ComboBox VerticalAlignment= "Center" ItemsSource= "{Binding EllipsoidList}" SelectedItem= "{Binding CurrentEllipsoid}" /> 3、Title= "{Binding Title}" 注意:标题也可绑定 |
经以上四步走,WPF数据绑定工作已经基本完成,实验证明该方法提高了程序的容错能力,以及程序数据结构的健壮性。
总结
到此这篇关于C# WPF数据绑定模板化操作的文章就介绍到这了,更多相关C# WPF数据绑定模板化内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://www.cnblogs.com/fzyyds/p/15762649.html