c# - WPF自定义控件库

标签 c# .net wpf

我正在尝试构建一个包含按钮和文本的自定义控件。当我尝试编译时出现以下错误。

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/

相关文章:

c# - 在 WPF 中使用单独的 ViewModel 将多个选项卡视为单独的 View

c# - 如何在代码隐藏中调用 Prism 事件

c# - Windows Mobile 6 GPS 精度

c# - 如何在使用 WCF 服务的 WPF 应用程序中集成 LDAP

c# - .net 应用程序在通过计划任务触发时失败

asp.net - 如何设置访问控制允许特定文件 web.config 上的来源

C# 将文件保存到内存并获取在以文件路径作为输入的方法中使用的路径

c# - 将类方法转换为IL并在运行时执行

c# - 使用反射查找ArrayList对象属性

c# - 使用 MVVM 范例用 c# 填充组合框