開發WPF應用程序,就不得不提MVVM。下面偶將展示MVVM中簡單的實現,其中主要在於ICommand的實現上,不過這種實現方式,應該不會有多少人在開發中使用,在此僅作學習使用。
准備:
界面繪制,簡單的以一個輸入框TextBox和一個按鈕Button組成。
入手
接下來寫ViewModel,注意其中ViewModel需要繼承接口INotifyPropertyChanged,其主要功能是保證后台屬性改變能夠通知到前台改變。
class TestViewModel : INotifyPropertyChanged
{
private string teststr;
/// <summary>
/// 待通知字符串
/// </summary>
public string TestStr
{
get { return teststr; }
set
{
teststr = value;
RaiseChanged("TestStr");
}
}
/// <summary>
/// 測試命令
/// </summary>
public ICommand TestCommand { get; set; }
public TestViewModel()
{
TestCommand = new TestCommand(this);
}
#region INotifyPropertyChanged接口實現
public void RaiseChanged(string propertyname)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
}
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
代碼中我們看到在TestViewModel中使用了一個TestCommand類。一下是此類的實現,其主要是ICommand的一個實現【開發中不建議使用】
class TestCommand : ICommand
{
public TestCommand(TestViewModel viemo)
{
viewmodel = viemo;
}
TestViewModel viewmodel{get;set;}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
int i = 0;
/// <summary>
/// 命令是否可用
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return true;
}
/// <summary>
/// 命令執行的操作
/// </summary>
/// <param name="parameter"></param>
public void Execute(object parameter)
{
i++;
viewmodel.TestStr = i.ToString();
}
}
最后就是將ViewModel內容綁定到界面啦!
XAML:
<Window x:Class="WPF_MVVM.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<TextBox Text="{Binding TestStr}"/>
<Button Grid.Row="1" Content="Test" Command="{Binding TestCommand}" />
</Grid>
</Window>
CodeBehind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new TestViewModel();
}
}
這樣一個簡單的MVVM程序就實現啦。哦,對了,這里未用到Model,可以說還不是一個完整的MVVM,這個就留給自己去思考吧。
項目代碼托管地址:https://wpfmvvm.codeplex.com/
