使用x:Class
屬性可讓您爲ResourceDictionary
定義代碼隱藏。 您必須指定該類的完整名稱空間(即x:Class="WpfApplication.MyClass"
),並且此類必須定義爲partial
(至少VS 2010抱怨且不使用此修飾符時不會編譯)。
我嘲笑,一個簡單的例子:
創建一個新的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
調用一些代碼的情況。
我選中了,這只是複製過去的錯誤。我有一次確定了這堂課。 – gtoulouse 2010-03-01 15:33:41