錯誤:“ResourceDictionary”根元素需要 x:Class 特性來支持 XAML 文件中的事件處理程序。請移除 MouseLeftButtonDown 事件的事件處理程序.
轉載於(https://social.msdn.microsoft.com/Forums/windowsapps/zh-CN/af3161ce-f020-4b0b-9b84-95ae597e53fd/resourcedictionary-xclass-xaml-mouseleftbuttondown-xclass?forum=wpfzhchs)
在資源字典中設置listboxItem的鼠標左擊的事件樣式。
打出這段代碼提示“ResourceDictionary”根元素需要 x:Class 特性來支持 XAML 文件中的事件處理程序。請移除 MouseLeftButtonDown 事件的事件處理程序,或將 x:Class 特性添加到根元素。 ”錯誤,
這句話是什麽意思?難道EventSetter 不能在資源字典中寫?
<ResourceDictionary xmlns="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>
<EventSetter Event="MouseLeftButtonDown" Handler="ProjectMouseLeftButtonDown"/>
<Style .Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#FF569BEE"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
解決思路:
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");
}
}
}
MainWindow.xaml:
<ListBox>
<ListBoxItem>Item 1</ListBoxItem>
<ListBoxItem>Item 2</ListBoxItem>
<ListBoxItem>Item 3</ListBoxItem>
</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>
錯誤:“ResourceDictionary”根元素需要 x:Class 特性來支持 XAML 文件中的事件處理程序。請移除 MouseLeftButtonDown 事件的事件處理程序.
