您的位置:首页 > 运维架构

wpf中INotifyPropertyChanged的用法

2015-07-06 18:16 246 查看
using System;
using System.Collections.Generic;
using System.ComponentModel;
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.Shapes;

namespace WpfApplication1
{
/// <summary>
/// Window9.xaml 的交互逻辑
/// </summary>
public partial class Window9 : Window
{
public Window9()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
class NotificationObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

public void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
class DelegateCommand : ICommand
{
//A method prototype without return value.
public Action<object> ExecuteCommand = null;
//A method prototype return a bool type.
public Func<object, bool> CanExecuteCommand = null;
public event EventHandler CanExecuteChanged;

public bool CanExecute(object parameter)
{
if (CanExecuteCommand != null)
{
return this.CanExecuteCommand(parameter);
}
else
{
return true;
}
}

public void Execute(object parameter)
{
if (this.ExecuteCommand != null) this.ExecuteCommand(parameter);
}

public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
class Model : NotificationObject
{
private string _wpf = "WPF";

public string WPF
{
get { return _wpf; }
set
{
_wpf = value;
this.RaisePropertyChanged("WPF");
}
}

public void Copy(object obj)
{
this.WPF += " WPF";
}

}
class ViewModel
{
public DelegateCommand CopyCmd { get; set; }
public Model model { get; set; }

public ViewModel()
{
this.model = new Model();
this.CopyCmd = new DelegateCommand();
this.CopyCmd.ExecuteCommand = new Action<object>(this.model.Copy);
}
}

}

________________________________

<Window x:Class="WpfApplication1.Window9"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window9" Height="300" Width="300">
<Grid>
<StackPanel VerticalAlignment="Top">
<TextBlock Text="{Binding model.WPF}" Height="208" TextWrapping="WrapWithOverflow"></TextBlock>
<Button Command="{Binding CopyCmd}" Height="93" Width="232" Content="Copy" Margin="30,0"/>
</StackPanel>
</Grid>
</Window>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: