2017-06-01 85 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查看更新。我的第一个回答是,如果它是一个完全原创的控件,而不是现有控件的一个子类,你将不得不这样做。如果它是一个子类,则通常可以继承默认模板。 –