我是 WPF 的新手,所以这可能是一个愚蠢的问题,但就是这样。
我正在尝试使用 XAML 事物创建自定义按钮,所以这就是我所拥有的:
<Button x:Class="Controls.ShinyButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" Height="40" Width="150">
<Button.Resources>
<ResourceDictionary Source=".\Resources.xaml" />
</Button.Resources>
<Border Background="{StaticResource BlueGradient}" CornerRadius="5">
<DockPanel>
<Image x:Name="imgIcon" DockPanel.Dock="Left" Height="32" Margin="4"/>
<TextBlock DockPanel.Dock="Right" Text ="Test" VerticalAlignment="Center" HorizontalAlignment="Left" Foreground="White" />
</DockPanel>
</Border>
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF02B6FF" Offset="0" />
<GradientStop Color="#FF0084F0" Offset="1" />
</LinearGradientBrush>
</Button.Background>
</Button>
设计者理解它并且编译没有错误,但是当我尝试运行程序并创建它的实例时,我收到错误:
“ContentControl 的内容必须是单个元素。”
我的资源文件是:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<LinearGradientBrush x:Key="BlueGradient">
<GradientStop Offset="0" Color="#FF02B6FF"/>
<!-- (2, 182, 255)-->
<GradientStop Offset="1" Color="#FF0084F0"/>
<!-- (0, 132, 240) -->
</LinearGradientBrush>
</ResourceDictionary>
我的边框内有 DockPanel,所以按钮只有一个孩子......
“ShinyButton”类看起来像这样:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Controls
{
/// <summary>
/// Interaction logic for ShinyButton.xaml
/// </summary>
public partial class ShinyButton : Button
{
public ShinyButton()
{
InitializeComponent();
}
}
}
在 main 函数中,我像这样添加它:
public MainWindow()
{
InitializeComponent();
ShinyButton shiny = new ShinyButton();
this.AddChild(shiny); //This is where the exception is thrown.
}
我究竟做错了什么?