2010-03-01 32 views
5

我有一個資源字典中的DataTemplate,在某些情況下,我需要按鈕,我不知道如何使用代碼來管理事件。在ResourceDictionary中添加.cs文件?

我試圖把一類在我的資源dictionnary這樣的:

<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    x:Class="SLProject.Templates" 
    x:Class="TVTemplate"> 

我在CS文件一樣,definied類:

namespace SLProject.Templates 
{ 
    partial class TVTemplate 
    { 

    } 
} 

構建是確定的,但在應用程序啓動後,我獲得XAML錯誤如下:

AG_E_PARSER_BAD_TYPE

我嘗試了我所知道的一切,比如將Class類更改爲ClassModifier,將類設爲繼承的RessourceDictionnary類...沒辦法。

有人有一個想法...

謝謝。

回答

0

您有兩次定義的x:Class屬性,這就是爲什麼你會得到解析器錯誤。更改你的聲明到這,它應該工作:

<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    x:Class="SLProject.Templates.TVTemplate"> 
+0

我選中了,這只是複製過去的錯誤。我有一次確定了這堂課。 – gtoulouse 2010-03-01 15:33:41

0

我檢查,它只是一個錯誤的複製過去。我有一次確定了這堂課。

6

使用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.添加新ResourceDictionaryResources.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調用一些代碼的情況。

0

最好的事情是製作你自己的用戶控件並添加你的事件。然後將這整個usercontrol放在資源字典中。

相關問題