在ResourceDictionary中添加.cs文件?

6

我在资源字典中有一个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">

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

namespace SLProject.Templates
{
    partial class TVTemplate
    { 

    }
}

构建过程正常,但在应用程序启动时,我遇到了以下XAML错误:

AG_E_PARSER_BAD_TYPE

我尝试了我所知道的所有方法,例如将类类型更改为ClassModifier,将类变成RessourceDictionnary的继承类等等,但都无济于事。

请问有人有想法吗?

谢谢。

4个回答

6
使用x:Class属性允许您为ResourceDictionary定义一个后台代码。 必须指定类的完整命名空间(即x:Class="WpfApplication.MyClass"),这样的类必须被定义为partial(至少VS 2010会抱怨并且不编译没有这个修饰符的类)。
我模拟了一个简单的例子: 1.创建一个新的WPF应用程序项目(WpfApplication2.添加一个新的类文件(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 中调用一些代码的情况。

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">

我检查了一下,这只是复制粘贴的错误。我已经定义了类一次。 - gtoulouse

0

我检查了一下,这只是复制粘贴的错误。我已经定义好了类。


0
最好的方法是制作自己的用户控件并在其中添加事件。 然后将整个用户控件放入资源字典中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接