学习WPF
WPF和Winform属于两套界面渲染方式。一个是对传统windows界面元素的封装,通过gdi绘制。另一个是全新的dx渲染绘制的界面,也脱离了对传统windows控件的依赖,没有历史包袱,理论上可以展现更炫酷的界面。对初级开发人员来说,没太大区别,类似的基本设计器是他们设计界面的主要手段,一样给事件编写代码。对初级以上开发人员来说,wpf需要学习xaml,有全新的ui描述语言,特别是可以通过模板的嵌套实现复杂的元素,通过style实现类似css的功能,通过比winform完善的多的数据绑定机制实现业务逻辑可以专心对数据而不是界面进行开发。前途来说,两者必定还会长期共存。深入理解winform对理解windows一些内部机制有好处。好好学习wpf可以更方便过度到其他xaml相关技术,这是微软目前广泛使用的技术,比如接下来的windows通用应用。
学习内容如下:
1. 数据绑定
2. 命令绑定
3. 自定立MVVM框架
4. 经典MVVM框架库
一、数据绑定:需要使用道德命名空间:Using System.ComponentModel
代码如下:
using System.ComponentModel
//数据绑定的基类
class ModelBase:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaizePropertyChanged(String porpertyName)
{
if(PropertyChanged!=null)
{
this.PropertyChanged.Invoke(this,new PropertyChangedArges(propertyName));
}
}
}
class MainViewModel:ModelBase
{
private string name;
public string Name{get return name;
set{
if(value!=this.name)
{
this.name=value;
RaizePropertyChanged("Name");
}
}
}
}
//XAML页面部分代码
<Window.Resource>
<Style>
<Setter Property="Control.FontSize" value="12"/>
</Style>
</Window.Resource>
<Button x:Name="bt1" text="{Binding Path=Name,Mode=Two Way}" Margin="100,100,100,100" />
//代码的cs代码加载
DataContent=new MainViewModel();
二、命令绑定:需要使用道德命名空间:Using System.Window.Input
代码如下:
//自定义类
class RelayCommand:ICommand
{
private event Action<object> _Execute;
private event Func<object,bool>_CanExecute;
public event EventHandler CanExecuteChanged;
public RelayCommand(Action<Object> action,Func<Object,bool> func)
{
this._Execute=action;
this._CanExecute=func;
}
public void Execute(Object parameter)
{
if(this._Execute==null) return;
this._Execute(parameter);
}
public bool CanExecute(Object parameter)
{
if(this._CanExecute==null) return true;
this._CanExecute(parameter);
}
}
//viewModel.cs代码
using System.Window.Input;
class MainViewModel
{
private ICommand textCommand;
public ICommand TextCommand{
set{
if(this.textCommand==null)
{
this.textCommand=new RelayCommand(Text,new Func<Object,bool> (o=>true));
}
}
}
public void Text()
{
Messagebox.Show("Hello world");
}
}
///xaml代码
<Button x:Name="bt1" Command={Binding TextCommand} CommandParameter="text">