WPF - ControlTemplate 上的事件?

发布于 2024-09-11 04:13:33 字数 352 浏览 3 评论 0原文

有谁知道为什么我无法在控件模板上设置事件?

例如,以下代码行将无法编译。它对控件模板中的任何事件执行此操作。

<ControlTemplate x:Key="DefaultTemplate" TargetType="ContentControl">
   <StackPanel Loaded="StackPanel_Loaded">

   </StackPanel>
</ControlTemplate>

我正在使用 MVVM 设计模式,此处的控件位于添加到应用程序的 MergedDictionaries 的 ResourceDictionary 中。

Does anyone know why I can't set an event on a control template??

For example, the following line of code will not compile. It does this with any events in a control template.

<ControlTemplate x:Key="DefaultTemplate" TargetType="ContentControl">
   <StackPanel Loaded="StackPanel_Loaded">

   </StackPanel>
</ControlTemplate>

I am using a MVVM design pattern and the control here is located in a ResourceDictionary that is added to the application's MergedDictionaries.

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

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

发布评论

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

评论(1

我爱人 2024-09-18 04:13:33

有谁知道为什么我无法在控件模板上设置事件?

实际上,您可以...但是您希望在哪里定义事件处理程序? ResourceDictionary 没有代码隐藏,因此没有地方放置事件处理程序代码。但是,您可以为资源字典创建一个类,并将其与 x:Class 属性关联:

<ResourceDictionary x:Class="MyNamespace.MyClass"
                    xmlns=...>

    <ControlTemplate x:Key="DefaultTemplate" TargetType="ContentControl">
       <StackPanel Loaded="StackPanel_Loaded">

       </StackPanel>
    </ControlTemplate>

C# 代码:(

namespace MyNamespace
{
    public partial class MyClass : ResourceDictionary
    {
        void StackPanel_Loaded(object sender, RoutedEventArgs e)
        {
            ...
        }
    }
}

您可能还需要将资源字典的构建操作更改为“Page “,具体记不太清了……)

Does anyone know why I can't set an event on a control template??

Actually, you can... But where would you expect the event handler to be defined ? The ResourceDictionary has no code-behind, so there is no place to put the event handler code. You can, however, create a class for your resource dictionary, and associate it with the x:Class attribute :

<ResourceDictionary x:Class="MyNamespace.MyClass"
                    xmlns=...>

    <ControlTemplate x:Key="DefaultTemplate" TargetType="ContentControl">
       <StackPanel Loaded="StackPanel_Loaded">

       </StackPanel>
    </ControlTemplate>

C# code :

namespace MyNamespace
{
    public partial class MyClass : ResourceDictionary
    {
        void StackPanel_Loaded(object sender, RoutedEventArgs e)
        {
            ...
        }
    }
}

(you might also need to change the build action of the resource dictionary to "Page", I don't remember exactly...)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文