2010-08-14 140 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