是的,有一個乾淨的方法來做到這一點。在WPF中使用Model-View-ViewModel pattern的一個方面(不是你必須使用這個)是命令。 WPF Commanding reference
這是從您的數據源對象暴露命令的簡單,但乾淨和公平的類型安全的框架類:
using System;
using System.Windows.Input;
namespace MVVM
{
/// <summary>
/// Defines a command that can be bound to from XAML and redirects to a handler function.
/// </summary>
public class ViewModelCommand : ICommand
{
private Action _handler;
public ViewModelCommand(Action handler)
{
_handler = handler;
}
#region ICommand Members
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_handler();
}
#endregion
}
/// <summary>
/// Defines a command that can be bound to from XAML and redirects to a handler function.
/// </summary>
public class ViewModelCommand<T> : ICommand
where T : class
{
private Action<T> _handler;
public ViewModelCommand(Action<T> handler)
{
_handler = handler;
}
#region ICommand Members
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_handler(parameter as T);
}
#endregion
}
}
你的數據源(例如,FootballPlayer類),則暴露了一個命令屬性如下:
/// <summary>
/// Tell the player to run. This particular command takes a string as a parameter.
/// </summary>
public ICommand RunCommand
{
get { return new ViewModelCommand<string>(run); }
}
實現的功能,在同FootballPlayer類,就可以是這樣的:
/// <summary>
/// Tell the player to run. This particular command takes a string as a parameter.
/// </summary>
public void search(string destination)
{
System.Windows.MessageBox.Show(destination, "Running to destination...");
}
最後,你的XAML具有以下綁定:
<Button Content="{Binding PlayerName}" FontSize="16" CommandParameter="{Binding Text, ElementName=txtDestination}" Command="{Binding RunCommand, Source={StaticResource ViewModelDataSource}}" />
(由於您使用一個DataTemplate,綁定的源將需要進行調整;但這是它的要點。我用這個在一類項目取得巨大成功 - 它允許邏輯和UI之間的一個非常乾淨的分離)
非常感謝!這當然是一個很好的解決方案。我當時告訴你實際情況,期望WPF支持「開箱即用」,這將允許以與普通屬性綁定相同的方式綁定事件,但我想這很值得期待。 – kubal5003 2010-06-04 17:32:22