【问题标题】:Need help handling events of a DataTemplate in the Application.xaml file需要帮助处理 Application.xaml 文件中的 DataTemplate 事件
【发布时间】:2009-03-30 13:45:37
【问题描述】:

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

我希望我很清楚。

【问题讨论】:

    标签: wpf event-handling datatemplate event-triggers


    【解决方案1】:

    您可以使用命令来实现这一点。让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)
    {
        ...
    }
    

    【讨论】:

    • 那你会如何在后面的代码中设置一些事件呢?如果我使用 ResourceDictionary(文件后面没有代码)并且我想引用 ResourceDictionary 页面本身中的处理程序。
    • 您可以轻松地为 ResourceDictionary 创建一个代码隐藏文件。见stackoverflow.com/questions/92100/…
    • 1) 请编辑第二个 sn-p,了解如何将事件发送给本地处理程序。 2) MyCommands 是什么,一个声明?
    • 1) 好的,已编辑。 2)您需要特别阅读命令和路由命令。
    • 我不想触发 ItemSelected 事件,我想触发 DataTemplate 按钮中的事件,因为模板中有很多按钮(即删除、编辑、上移、下移和更多的按钮)。谢谢。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-23
      • 1970-01-01
      • 2017-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多