我正在尝试构建一个包含按钮和文本的自定义控件。当我尝试编译时出现以下错误。
Error 1 'ResourceDictionary' root element requires a x:Class attribute to support event handlers in the XAML file. Either remove the event handler for the Click event, or add a x:Class attribute to the root element.
我的代码:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:textbtn">
<Style TargetType="{x:Type local:CustomControl1}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl1}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid>
<TextBlock Text="This is a Test" Foreground="Aqua" Background="AntiqueWhite"/>
<Button Content="Button" Height="23" HorizontalAlignment="bottom" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
最佳答案
错误的意思正是它所说的。单击事件处理程序实际上执行以下操作:
myButtonName.Click += myClass.ClickHandlerName;
如果您没有为资源字典分配类,它就不知道将点击处理程序分配给什么!
因为控件模板不应该与后面代码中的特定类紧密耦合,所以我会从模板中完全删除点击处理程序。无论如何,在 MVVM 中,命令是更好的选择。
关于c# - WPF自定义控件库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23095580/