我正在努力解决以下这个问题。我在资源目录中的样式文件。但它不能将click方法应用于上下文菜单项。它显示在此错误下方。请帮助我如何实现这一目标。
错误:“'无法在文本'OnMenuItemClick'中创建'点击'。'行号“10”和行位置“35”。“
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:src="clr-namespace:System;assembly=mscorlib"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ObjectDataProvider x:Key="date" ObjectType="{x:Type src:DateTime}"/>
<Style x:Key="ContextMenuStyle1" TargetType="{x:Type ContextMenu}">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Style>
<ContextMenu x:Key="ListViewContext" Style="{StaticResource ContextMenuStyle1}">
<MenuItem Header="Create" Click="OnMenuItemClick" CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"></MenuItem>
</ContextMenu>
<ContextMenu x:Key="GridItemContext" Style="{StaticResource ContextMenuStyle1}">
<MenuItem Header="Modify" CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"/>
<MenuItem Header="Delete" CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"/>
</ContextMenu>
<Style x:Key="ListViewGrid" TargetType="{x:Type ListView}">
<Setter Property="BorderBrush" Value="#FFDFDFE2"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Background" Value="#faf2f2"/>
<Setter Property="ContextMenu" Value="{StaticResource ListViewContext}"/>
</Style>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="ContextMenu" Value="{StaticResource GridItemContext}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListViewItem">
<Border CornerRadius="0" SnapsToDevicePixels="True" >
<Border Name="InnerBorder" CornerRadius="0" BorderThickness="0,0,0,1" BorderBrush="#FFDFDFE2">
<Grid Background="#FFEFEFEF" Name="Trg" Height="20">
<GridViewRowPresenter />
</Grid>
</Border>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Trg" Property="Background" Value="#FFDFDFE2" />
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="Trg" Property="Background" Value="#FFDFDFE2" />
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsSelected" Value="True" />
<Condition Property="IsMouseOver" Value="True" />
</MultiTrigger.Conditions>
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
答案 0 :(得分:1)
当我尝试上面的代码时,我得到的错误是:
错误1“ResourceDictionary”根元素需要x:Class属性 支持XAML文件中的事件处理程序。删除事件 Click事件的处理程序,或者向根添加x:Class属性 元件。第10行第35位
这就是我修复它的方法:
1)在ResourceDictionary
:
x:Class="WpfApplication4.Dictionary1"
2)在项目中添加了一个C#类文件,代码如下:
public partial class Dictionary1 : ResourceDictionary
{
public Dictionary1()
{
InitializeComponent();
}
void OnMenuItemClick(object sender, RoutedEventArgs e)
{
}
}
然后,项目建好了。