我是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();
}
}
}
在主函数中,我像这样添加它:
public MainWindow()
{
InitializeComponent();
ShinyButton shiny = new ShinyButton();
this.AddChild(shiny); //This is where the exception is thrown.
}
我究竟做错了什么?
最佳答案
只是一个猜测,我无法测试它,但是请尝试以下代码:
<Button.Template>
<ControlTemplate>
<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>
</ControlTemplate>
</Button.Template>
编辑:确定下一次尝试:
而不是将ShinyButton添加到窗口中(删除this.AddChild(shiny)),请尝试通过添加以下代码将ShinyButton添加到网格中:
NameOfGrid.Children.Add(shiny);
出现此错误的原因是,您的Window只能有一个孩子,我敢打赌,您的情况已经有一个网格作为该孩子。
关于wpf - “ContentControl的内容必须是单个元素。”异常(exception),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12609724/