在ResourceDictionary中添加.cs?

gto*_*use 5 .net c# xaml expression-blend silverlight-4.0

我在一个资源词典中有DataTemplate,在某些情况下,我需要按钮,我不知道如何使用代码来管理事件.

我试着在我的资源字典中放一个类:

<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">
Run Code Online (Sandbox Code Playgroud)

我在cs文件中定义了这样的类:

namespace SLProject.Templates
{
    partial class TVTemplate
    { 

    }
}
Run Code Online (Sandbox Code Playgroud)

构建是正常的但是当应用程序启动时,我获得了以下XAML错误:

AG_E_PARSER_BAD_TYPE

我尝试了所有我知道的将类类更改为ClassModifier,使类成为继承的RessourceDictionnary类...没办法.

有人有想法......

谢谢.

Bla*_*ise 6

使用该x:Class属性可以为a定义代码隐藏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!");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

在示例中,我从a连接了一个双击事件Style,因为它是一个需要你从一个代码中调用一些代码的场景ResourceDictionary.


Ste*_*ner 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">
Run Code Online (Sandbox Code Playgroud)