【发布时间】:2009-03-30 13:45:37
【问题描述】:
我的应用程序中有一个包含几个按钮的数据模板。 我希望在当前页面(我在许多页面中使用此模板)而不是在 Application.xaml.vb/cs 文件中触发这些按钮的偶数处理程序,因为我希望在每个页面上执行不同的操作。
我希望我很清楚。
【问题讨论】:
标签: wpf event-handling datatemplate event-triggers
我的应用程序中有一个包含几个按钮的数据模板。 我希望在当前页面(我在许多页面中使用此模板)而不是在 Application.xaml.vb/cs 文件中触发这些按钮的偶数处理程序,因为我希望在每个页面上执行不同的操作。
我希望我很清楚。
【问题讨论】:
标签: wpf event-handling datatemplate event-triggers
您可以使用命令来实现这一点。让Buttons 中的DataTemplate 执行特定的Commands:
<Button Command="{x:Static MyCommands.SomeCommand}"/>
然后让每个使用DataTemplate 的视图处理Command:
<UserControl>
<UserCommand.CommandBindings>
<CommandBinding Command="{x:Static MyCommands.SomeCommand}"
Executed="_someHandler"/>
</UserCommand.CommandBindings>
</UserControl>
在 cmets 之后编辑:一旦您按照 these instructions 为您的 ResourceDictionary 创建了代码隐藏,您就可以简单地以通常的方式连接事件:
在MyResources.xaml:
<ListBox x:Key="myListBoxResource" ItemSelected="_listBox_ItemSelected"/>
然后在MyResources.xaml.cs:
private void _listBox_ItemSelected(object sender, EventArgs e)
{
...
}
【讨论】:
如果你使用事件而不是命令,那么在你的 Click 事件处理程序中只写
private void Button_Click(object sender, RoutedEventArgs e)
{
var dataItem = (FrameworkElement)sender).DataContext;
// process dataItem
}
【讨论】: