我试图建立一个具有按钮和文本的自定义控件。当我尝试编译时,出现以下错误。


  错误1'ResourceDictionary'根元素需要一个x:Class属性来支持XAML文件中的事件处理程序。删除Click事件的事件处理程序,或将x:Class属性添加到根元素。


我的代码:

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

最佳答案

该错误由LordTakkera很好地解释了,但是他不希望将简单的解决方案应用于他的答案,因此,为了澄清这一点,向资源字典提供类名将允许您像在其他控件中一样使用事件处理程序:

<ResourceDictionary
    x:Class="ResourceDictionaryClass1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:textbtn">


但是LordTakkera确实正确:命令是实现ui回调的一种干净方法。

关于c# - WPF自定义控件库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23095580/

10-12 00:29
查看更多