c# - 发生 "Ensure Event Failed"错误

标签 c# wpf custom-controls

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:CustomCalc">
    <Style TargetType="{x:Type local:CustomControl1}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:CustomControl1}">

                    <TextBlock Text="welcome" Height="50" Width="150" MouseDown=""/>

                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

在上面的程序中,(在我在自定义控件库中锻炼的程序中) 我正在尝试更改控件文本 block => 按钮。(文本 block 充当按钮功能) 所以我尝试向文本 block 添加一个事件,它给出了一条错误消息“确保事件失败”, 这个文件名为“Generic.xaml”,所以我添加了一个类“Generic.xaml.cs”,但显示了同样的错误。 请解释它为什么会发生以及如何解决它,在此先感谢。

最佳答案

您需要添加 x:Class 属性以支持 XAML 文件中的事件处理程序。所以你的 Generic.xaml 应该是这样的:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:CustomCalc"
    x:Class="CustomCalc.Generic">
    <Style TargetType="{x:Type local:CustomControl1}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:CustomControl1}">
                    <TextBlock Text="welcome" Height="50" Width="150" MouseDown="TextBlock_MouseDown"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

至于 Generic.xaml.cs :

namespace CustomCalc
{
    public partial class Generic : ResourceDictionary
    {
        private void TextBlock_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {

        }
    }
}

另外不要忘记将您的 ResourceDictionary 合并到 App.Xaml 文件中:

<Application.Resources>
    <ResourceDictionary >
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/CustomCalc;component/Generic.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

关于c# - 发生 "Ensure Event Failed"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33094622/

相关文章:

wpf - 到 ScaleTransform 的模板绑定(bind)在自定义控件中不起作用

c# - 为 TextBox 或代码解决方法寻找 DisplayMemberPath 的替代方法

WPF 打印流程文档

c# - 读取xml属性

c# - 强制将 XML 字符实体放入 XmlDocument 中

c# - 如何阻塞一个线程,直到另一个线程在 C# 中获得服务器响应

wpf - 在WPF MVVM中,如何生成在UI线程上运行回调的后台任务?

c# - 如何从后面的代码访问我的 ViewModel

c++ - WIN32 对话框上的自定义颜色形状

C# 可以将 "program"类部分用于控制台应用程序吗?