在资源字典中设置listboxItem的鼠标左击的事件样式。
打出这段代码提示“ResourceDictionary”根元素需要 x:Class 特性来支持 XAML 文件中的事件处理程序。请移除 MouseLeftButtonDown 事件的事件处理程序,或将 x:Class 特性添加到根元素。 ”错误,
这句话是什么意思?难道EventSetter 不能在资源字典中写?
"http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1">
<Style x:Key="remenber" TargetType="{x:Type ListBoxItem}" >
<Setter Property="Margin" Value="1">Setter>
"MouseLeftButtonDown" Handler="ProjectMouseLeftButtonDown"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#FF569BEE">Setter>
Trigger>
Style.Triggers>
Style>
解决思路:
1.首先,EventSetter 是可以在资源字典中写的。那句提示意思是需要在ResourceDictionary标签内加上x:Class特性。
你可以写成这样:
ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
x:Class="命名空间.资源字典的名称" >
命名空间:以你的代码为例,此处应为”WpfApplication1”
资源字典的名称:如果资源字典文件是”Dictionary1.xaml”,这里就是”Dictionary1”
完整写法就是 x:Class=”WpfApplication1. Dictionary1”
2.下面的Demo供你参考:
Dictionary1.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WriteEventInResourceDictionary"
x:Class="WriteEventInResourceDictionary.Dictionary1">
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="MyCustomMouseEvent"/>
Style>
ResourceDictionary>
Dictionary1.xaml.cs:
namespace WriteEventInResourceDictionary
{
public partial class Dictionary1
{
private void MyCustomMouseEvent(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello");
}
}
}
MainWindow.xaml:
<ListBox>
<ListBoxItem>Item 1ListBoxItem>
<ListBoxItem>Item 2ListBoxItem>
<ListBoxItem>Item 3ListBoxItem>
ListBox>
App.xaml:
<Application x:Class="WriteEventInResourceDictionary.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WriteEventInResourceDictionary"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Dictionary1.xaml" />
ResourceDictionary.MergedDictionaries>
ResourceDictionary>
Application.Resources>
Application>