我想要一些建议来实现这个功能,设计整洁,没有任何代码复制。在大多数视图中,我有一个具有许多视图和网格控件的应用程序。我需要添加一个导出功能(将记录导出到excel)。网格控件支持这个OOB,只需要调用'Grid.Export()'。我正在计划每个网格侧面的UI按钮并调用此方法。
所以,显然我需要在代码隐藏中编写代码,因为我需要控件的实例来调用方法。但是,我喜欢将代码保存在一个地方,并以某种方式调用所有Xamls中的代码。 (所有WPF观点)。
一种技术是编写一个BaseView类并从中派生所有视图。
但是想知道WPF是否支持我可以实现这一目标的任何技术。 (行为等......?)
谢谢, 摩尼
答案 0 :(得分:3)
创建一个包含数据网格和导出按钮的UserControl
。实际上,让它成为网格本身的一部分。
在所有视图中使用此UserControl
代替默认数据网格,您就完成了。
此外,如果您必须修改按钮的外观或其行为,您只有一个地方可以更改它,并且它将在您的所有视图中更新。
答案 1 :(得分:0)
其中一个解决方案是使用WPF路由命令。
注意:我写这个答案时假设您的“View”是Window类的子类。
首先,将自定义路由命令添加到项目中。
public static class MyCommands
{
private static readonly RoutedUICommand exportCommand = new RoutedUICommand("description", "Export", typeof(MyCommands));
public static RoutedUICommand ExportCommand
{
get
{
return exportCommand;
}
}
}
在每个视图中,将自定义命令设置为Button.Command并将目标对象绑定到Button.CommandTarget。
<Button Command="local:MyCommands.ExportCommand" CommandTarget="{Binding ElementName=dataGrid1}">Export</Button>
最后,在您的Application类(默认名为App)中,在自定义命令和Window之间注册一个命令绑定。
public partial class App : Application
{
public App()
{
var binding = new CommandBinding(MyCommands.ExportCommand, Export, CanExport);
CommandManager.RegisterClassCommandBinding(typeof(Window), binding);
}
private void Export(object sender, ExecutedRoutedEventArgs e)
{
// e.Source refers to the object is bound to Button.CommandTarget.
var dataGrid = (DataGrid)e.Source;
// Export data.
}
private void CanExport(object sender, CanExecuteRoutedEventArgs e)
{
// Assign true to e.CanExecute if your application can export data.
e.CanExecute = true;
}
}
现在,当用户点击按钮时会调用App.Export。
示例可用here。