使用x:Class 属性允许您为ResourceDictionary 定义代码隐藏。
您必须指定类的完整命名空间(即x:Class="WpfApplication.MyClass"),并且此类必须定义为partial(至少VS 2010会抱怨并且没有这样的修饰符不会编译)。
我模拟了一个简单的例子:
1.新建一个WPF应用项目(WpfApplication)
2.添加一个新的类文件(TestClass.cs)并粘贴以下代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Windows;
namespace WpfApplication
{
public partial class TestClass
{
private void OnDoubleClick(object obj, MouseButtonEventArgs args)
{
MessageBox.Show("Double clicked!");
}
}
}
3.添加新的ResourceDictionary (Resources.xaml),打开文件并粘贴以下代码
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfApplication.TestClass">
<Style TargetType="{x:Type Label}">
<EventSetter Event="Label.MouseDoubleClick" Handler="OnDoubleClick"/>
</Style>
</ResourceDictionary>
4.最后,打开MainWindow.xaml并输入以下代码
<Window x:Class="WpfApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ResourceDictionary Source="Resources.xaml"/>
</Window.Resources>
<Grid>
<Label Content="Double click here..." HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Background="Red"/>
</Grid>
</Window>
在示例中,我从Style 连接了一个双击事件,因为这是一个需要您从ResourceDictionary 调用一些代码的场景。