【问题标题】:Adding an eventhandler to ContextMenuItem in template file在模板文件中向 ContextMenuItem 添加事件处理程序
【发布时间】:2014-10-29 21:48:56
【问题描述】:

我正在尝试在模板文件中添加上下文菜单以及上下文菜单项和处理程序。前面的东西很好,但是VS不会让我在模板文件中的菜单项中添加一个事件处理程序,看起来像这样

<ControlTemplate TargetType="{x:Type local:CalendarDayView}">
                    <ControlTemplate.Resources>
                        <ContextMenu x:Key="dayEntryContextMenu">
                            <MenuItem Header="Remove entry" Click="removeEntryBtn"/>
                        </ContextMenu>
                    </ControlTemplate.Resources>
                    <Border BorderBrush="Gray" BorderThickness="1" Width="100" Height="100">
                        <Grid Name="contentGrid">
                        <ListBox Name="entriesListBox" Background="LightYellow" ContextMenu="{StaticResource dayEntryContextMenu}">
                            <ListBoxItem>Test entry #1</ListBoxItem>
                            <ListBoxItem>Test entry #2</ListBoxItem>
                            <ListBoxItem>Test entry #3</ListBoxItem>
                        </ListBox>
                        <!-- Date display below -->
                        <TextBlock Name="dateTextBlock" Text="31-Nov" FontFamily="Segoe UI Light" FontSize="18" VerticalAlignment="Bottom" HorizontalAlignment="Right"/>
                        </Grid>
                    </Border>
                </ControlTemplate>

我得到的错误是 错误 1“ResourceDictionary”根元素需要 x:Class 属性来支持 XAML 文件中的事件处理程序。删除 Click 事件的事件处理程序,或将 x:Class 属性添加到根元素。第 37 行位置 61。

有什么办法可以做到吗?

【问题讨论】:

    标签: c# wpf xaml custom-controls eventhandler


    【解决方案1】:

    问题是您的事件处理程序需要在代码隐藏文件中实现,但由于您只有 xaml 文件而没有任何 *.cs 文件,VS 不知道您的事件处理程序应该在哪里实现。

    要解决此问题,您需要为您的 xaml 文件添加一个代码隐藏文件。在该文件后面的代码中,您必须定义资源字典的类(存储 ControlTemplate 的位置),然后您可以在 xaml 文件中定义“x:class”属性。之后,您应该能够定义您的事件处理程序。

    查看更完整的描述here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多