代码之家  ›  专栏  ›  技术社区  ›  Rachel

WPF-ControlTemplate上的事件?

  •  8
  • Rachel  · 技术社区  · 14 年前

    有人知道为什么我不能在控件模板上设置事件吗??

    例如,下面的代码行不会编译。它对控件模板中的任何事件执行此操作。

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

    我使用的是MVVM设计模式,这里的控件位于添加到应用程序的mergeddictionary的ResourceDictionary中。

    1 回复  |  直到 14 年前
        1
  •  11
  •   Thomas Levesque    14 年前

    有人知道为什么我不能在控件模板上设置事件吗??

    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”,我不太清楚……)

    推荐文章