2017-06-01 39 views
0

我想創建一個簡單的自定義控件,它可以擴展TextBoxWPF自定義控件是空的

我通過Add -> New Item... -> Custom Control創建它,我對自動生成的代碼進行了一些更改。我將CustomControl的基類更改爲TextBox,並刪除Theme/Generic.xaml文件中的Template setter。

但是,當我將它添加到MainWindow並運行時,它是空白的。這是我的最終代碼:

文件Theme/Generic.xaml

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

    <Style TargetType="{x:Type local:CustomControl}"> 
     <Setter Property="BorderThickness" Value="10"/> 
    </Style> 

</ResourceDictionary> 

文件CustomControl.cs

namespace Test 
{ 
    public class CustomControl : TextBox 
    { 
     static CustomControl() 
     { 
      DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl), new FrameworkPropertyMetadata(typeof(CustomControl))); 
     } 
    } 
} 
+0

的問題是,你忘了初始化控制。 – macieqqq

+0

你想通過使用自定義控件來實現什麼?爲了造型,你可以使用一種風格,例如 - 繼承的構成。 –

+0

@macieqqq以及如何初始化? – crupest

回答

1

有什麼也沒有。它需要一個模板。

有兩種方法可以做到這一點:首先,最簡單的方法是將Style設置爲TextBox的默認樣式。這會給你默認模板和其他一切默認樣式。如果願意,可以隨意添加setter以覆蓋繼承的。

<Style 
    TargetType="{x:Type local:MyCustomControl}" 
    BasedOn="{StaticResource {x:Type TextBox}}" 
    > 
    <Setter Property="BorderThickness" Value="10"/> 
    <Setter Property="BorderBrush" Value="Black"/> 
</Style> 

其次,編寫自己的模板。如果你發現你需要做任何默認模板不會爲你做的事情,你會這樣做。但要小心,控制行爲總是比天真地假設要複雜得多。有時這些可能是深水。

Here's some documentation about retemplating a TextBox or a subclass of a TextBox

你需要在大量的填補比這更多的特性,但在這裏是一個開始:

<Style 
    TargetType="{x:Type local:MyCustomControl}" 
    BasedOn="{StaticResource {x:Type TextBox}}" 
    > 
    <Setter Property="BorderThickness" Value="10"/> 
    <Setter Property="BorderBrush" Value="Black"/> 

    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type local:CustomControl}"> 
       <Border 
        BorderThickness="{TemplateBinding BorderThickness}" 
        BorderBrush="{TemplateBinding BorderBrush}" 
        > 
        <ScrollViewer Margin="0" x:Name="PART_ContentHost"/> 
       </Border> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 
+0

它的工作原理。但順便說一句,你能告訴我爲什麼模板屬性是強制性需要的嗎? – crupest

+0

@crupest查看更新。我的第一個回答是,如果它是一個完全原創的控件,而不是現有控件的一個子類,你將不得不這樣做。如果它是一個子類,則通常可以繼承默認模板。 –