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