2009-12-05 60 views
1

后自动出现了C#代码文件 - MyCustomControl.cs:在WPF中应该将XAML用于自定义控件的布局?创建自定义的控制有

public class MyCustomControl : ContentControl { 
    static MyCustomControl() { 
     ... 
     DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), 
     new FrameworkPropertyMetadata(typeof(MyCustomControl))); 
     } 
     ... 
} 

和文件默认梃 - 主题\ Generic.xaml:

<!-- themes/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:CustomControlLib"> 
    <Style TargetType="{x:Type local:MyCustomControl}"> 
    <Setter Property="Template"> 
    <Setter.Value> 
     <ControlTemplate TargetType="{x:Type local:MyCustomControl}"> 
     <Border Background="{TemplateBinding Background}" 
       BorderBrush="{TemplateBinding BorderBrush}" 
       BorderThickness="{TemplateBinding BorderThickness}"> 
     <ContentPresenter /> 
     </Border> 
     </ControlTemplate> 
    </Setter.Value> 
    </Setter> 
    </Style> 
</ResourceDictionary> 

但是,在如何应我正确地放置自定义控件本身的布局和内容的XAML代码?

回答

3

自定义控件的(默认)布局和内容由generic.xaml中的ControlTemplate定义。因此,您应该将布局和内容放置在为您生成的ControlTemplate元素中。 (请注意,ContentPresenter将显示控件用户提供的内容:您只需提供作为模板一部分的“内容”,例如在复选框中,模板将提供小方块,但用户内容将提供标题)

+0

是的,我尝试这样做,但在这种情况下,我得到一个错误:“属性'视觉树'被设置多次”(如果我把元素放在“边框”元素旁边)或“ property'Child'不止一次设置“(如果我在”Border“元素中放置了两个以上的元素)。我做错了什么? – rem 2009-12-05 20:30:58

+1

看来我意识到:我只是应该添加一个包装元素,像StackPanel之类的东西。 谢谢! – rem 2009-12-05 20:38:11