views:

266

answers:

1

After custom control is created there automatically appeared file for C# code - MyCustomControl.cs:

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

and file for default stile - Themes\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>

But where and how should I correctly place XAML code for layout and content of Custom Control itself?

+2  A: 

The (default) layout and content of the custom control is defined by the ControlTemplate in generic.xaml. So you should put the layout and content within the ControlTemplate element that has been generated for you. (Note that the ContentPresenter will display content provided by users of your control: you need only to provide "content" that is part of your template, e.g. in a check box, your template would provide the little square but user content would provide the caption.)

itowlson
Yes, I try to do so but in this case I get an error: "The property'Visual Tree' is set more than once" (if i put element beside the "Border" element") or "The property'Child' is set more than once" (if i put more than two elements inside the "Border" element"). What I do wrong?
rem
It seems I realize: I simply should add a wrapping element, something like StackPanel or the like..Thank you!
rem