2010-08-14 138 views
1

我想知道是否可以制作自定义形状自定义控件。 我需要做出包含文本框的控件,但是控件的形状必须比普通的矩形/正方形更复杂。WPF自定义形状控件

回答

2

简短答案是肯定的。 长的答案是阅读WPF控制风格:

<Window 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    x:Class="WpfApplication1.MainWindow" 
    x:Name="Window" 
    Title="MainWindow" 
    Width="640" 
    Height="480"> 

    <Window.Resources> 
     <Style x:Key="TextBoxSample" TargetType="{x:Type TextBox}"> 
      <Setter Property="FontWeight" Value="Bold"/> 
      <Setter Property="Template"> 
       <Setter.Value> 
        <ControlTemplate TargetType="{x:Type TextBox}"> 
         <Grid> 
          <Ellipse 
           x:Name="Border" 
           Stroke="#FF393785" 
           StrokeThickness="2" 
           > 
           <Ellipse.Fill> 
            <RadialGradientBrush GradientOrigin="0.25,0.25" RadiusY="0.75" RadiusX="0.75"> 
             <GradientStop Color="White" Offset="0.2"/> 
             <GradientStop Color="#FF2EC452" Offset="0.5"/> 
             <GradientStop Color="#FF606060" Offset="1"/> 
            </RadialGradientBrush> 
           </Ellipse.Fill> 
           </Ellipse>        
          <!-- The implementation places the Content into the ScrollViewer. It must be named PART_ContentHost for the control to function --> 
          <ScrollViewer 
           x:Name="PART_ContentHost" 
           Background="Transparent" 
           HorizontalAlignment="Center" 
           VerticalAlignment="Center" 
           /> 
         </Grid> 
         <ControlTemplate.Triggers> 
          <Trigger Property="IsEnabled" Value="False"> 
           <Setter Property="Fill" Value="#000" TargetName="Border"/> 
          </Trigger> 
         </ControlTemplate.Triggers> 
        </ControlTemplate> 
       </Setter.Value> 
      </Setter> 
     </Style> 

    </Window.Resources> 
    <Grid x:Name="LayoutRoot"> 
     <TextBox 
      Style="{StaticResource TextBoxSample}" 
      VerticalAlignment="Center" 
      HorizontalAlignment="Center" 
      Text="TextBox" 
      Width="180" 
      Height="180" 
      /> 
    </Grid> 
</Window> 
+0

看起来很有趣,但为什么你在模板中使用网格?独家elipse不会工作? 还有一个问题你使用了x:Type TextBox,我可以使用更通用的类型,比如UserControl,或者我可以在TargetType中使用两个值? – Berial 2010-08-15 09:32:15

+0

Ellipse不是ContentControl,因此无法容纳ScrollViewer(TextBox控件将放置TextBox的内容)。注:网格是基本布局面板之一。这不是一个DataGrid。您可以将TextBox的基类指定为TargetType,但不会像您期望的那样工作PART_ConentHost专门用于TextBox。您可以制作其他样式可以基于的样式。哦,永远不要定义UserControls类。这对于WPF来说只是一个非常糟糕的模式。 不幸的是从WinForms转移到WPF。想到这件事让我感到悲伤。 – FuleSnabel 2010-08-15 10:17:55

+0

感谢您的解释,但我仍然有问题来实现我的目标。 我需要创建形状的custon控制这样 <多边形点=” 0 0,40 0,60 20,40 40,0 40" 填充= “红色”> 或至少我需要插入这个多边形两个文本框。 但我认为这是不可能的。 XAML阻止我将任何文本框放置在多边形内:(还有什么是我需要这个多边形来填充整个可用空间(多边形将放置在网格中,我猜想)是否可以这样做? – Berial 2010-08-15 11:14:59