需要帮助处理 Application.xaml 文件中 DataTemplate 的事件

发布于 2024-07-16 11:01:59 字数 139 浏览 4 评论 0 原文

我的应用程序中有一个包含几个按钮的数据模板。 我希望这些按钮的偶数处理程序在当前页面(我在许多页面中使用此模板)而不是在 Application.xaml.vb/cs 文件中触发,因为我希望在每个页面上执行不同的操作。

我希望我说清楚了。

I have in my application a data template that has a few buttons.
I want those buttons' even handler to be fired in the current page (I am using this template in many pages) rather than in the Application.xaml.vb/cs file, since I want different actions on each page.

I hope I am clear.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦年海沫深 2024-07-23 11:01:59

您可以使用命令来实现此目的。 让 DataTemplate 中的 Button 执行特定的 Command

<Button Command="{x:Static MyCommands.SomeCommand}"/>

然后让使用该 DataTemplate 的每个视图处理Command

<UserControl>
    <UserCommand.CommandBindings>
         <CommandBinding Command="{x:Static MyCommands.SomeCommand}"
                         Executed="_someHandler"/>
    </UserCommand.CommandBindings>
</UserControl>

在注释后编辑:按照ResourceDictionary创建代码隐藏后.com/questions/92100/is-it-possible-to-set-code-behind-a-resource-dictionary-in-wpf-for-event-handli">这些说明,您可以简单地连接事件按照通常的方式:

MyResources.xaml 中:

<ListBox x:Key="myListBoxResource" ItemSelected="_listBox_ItemSelected"/>

然后在 MyResources.xaml.cs 中:

private void _listBox_ItemSelected(object sender, EventArgs e)
{
    ...
}

You can use commanding to achieve this. Have the Buttons in the DataTemplate execute specific Commands:

<Button Command="{x:Static MyCommands.SomeCommand}"/>

Then have each view that uses that DataTemplate handle the Command:

<UserControl>
    <UserCommand.CommandBindings>
         <CommandBinding Command="{x:Static MyCommands.SomeCommand}"
                         Executed="_someHandler"/>
    </UserCommand.CommandBindings>
</UserControl>

EDIT after comments: Once you have created a code-behind for your ResourceDictionary as per these instructions, you can simply connect events in the usual fashion:

In MyResources.xaml:

<ListBox x:Key="myListBoxResource" ItemSelected="_listBox_ItemSelected"/>

Then in MyResources.xaml.cs:

private void _listBox_ItemSelected(object sender, EventArgs e)
{
    ...
}
生生漫 2024-07-23 11:01:59

如果您使用事件而不是命令,那么在您的 Click 事件处理程序中只需编写

private void Button_Click(object sender, RoutedEventArgs e)
{
    var dataItem = (FrameworkElement)sender).DataContext;
    // process dataItem
}

If you use events and not commands, then in your Click event handler just write

private void Button_Click(object sender, RoutedEventArgs e)
{
    var dataItem = (FrameworkElement)sender).DataContext;
    // process dataItem
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文