在资源字典中设置listboxItem的鼠标左击的事件样式。

<EventSetter Event="MouseLeftButtonDown"  Handler="ProjectMouseLeftButtonDown"/> 打出这段代码提示“ResourceDictionary”根元素需要 x:Class 特性来支持 XAML 文件中的事件处理程序。请移除 MouseLeftButtonDown 事件的事件处理程序,或将 x:Class 特性添加到根元素。 ”错误,

   
这句话是什么意思?难道EventSetter 不能在资源字典中写?

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="命名空间.资源字典的名称" >

    </ResourceDictionary>
 命名空间:以你的代码为例,此处应为"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");

     }

     }

    }
posted @ 2017-07-18 16:17  Let‘sGo  阅读(319)  评论(0编辑  收藏  举报