我目前正在为我的自定义类型(比如 FootballPlayer)编写 DataTemplate。在此模板中我想放置 ie.按钮并让该按钮在单击时调用一些 FootballPlayer 函数,例如。运行()。
是否有任何简单或复杂但干净的方法来实现这种行为?
我相信 DataTemplate 知道有关我的对象的所有信息,因为设置了 DataType 并且包含了 clr-namespace。
<DataTemplate DataType="{x:Type my:FootballPlayer}">
</DataTemplate>
我认为有一种干净的方法可以实现这一目标。谁能告诉我怎么做?
//编辑 解决方案不必是干净的。现在,经过一番调查,我只是在寻找任何可以调用函数/在被绑定(bind)的对象上引发事件的解决方案。
最佳答案
是的,有一种干净的方法可以做到这一点。使用 Model-View-ViewModel pattern 的一方面在 WPF 中(并不是说您必须使用它)是命令。 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 具有以下数据绑定(bind):
<Button Content="{Binding PlayerName}" FontSize="16" CommandParameter="{Binding Text, ElementName=txtDestination}" Command="{Binding RunCommand, Source={StaticResource ViewModelDataSource}}" />
(由于您使用的是 DataTemplate,因此需要调整绑定(bind)的源;但这就是它的要点。我在一个类项目中使用它并取得了巨大成功 - 它允许在逻辑和用户界面。)
关于WPF DataTemplate 事件绑定(bind)到对象函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2974981/