Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Create instances of controls defined in xaml

Tags:

c#

wpf

I have a control defined in xaml with a fairly large number of properties set that is difficult to reproduce in code behind. Can I define the control in xaml and somehow create instances of it in the code behind?

like image 976
Aks Avatar asked Mar 28 '11 13:03

Aks


People also ask

What are controls in XAML?

The XAML User Interface framework offers an extensive library of controls that supports UI development for Windows. Some of them have a visual representation such Button, Textbox, TextBlock, etc.; while other controls are used as containers for other controls or content, for example, images.

What is the difference between user control and custom control in WPF?

A customControl can be styled and templated and best suited for a situation when you are building a Control Library. On the contrary, a UserControl gives you an easy way to define reusable chunk of XAML which can be reused widely in your application and when you don't need to use it as a Control Library .


2 Answers

Another option is to create the control as a resource with the x:Shared="False" property if you want to get new instances on each resolution:

<UserControl.Resources>
  <Rectangle x:Key="MyControl" x:Shared="False" 
             ...
             />
</UserControl.Resources>

In code:

var myNewCtrl = this.FindResource("MyControl") as Rectangle;
// use control
like image 184
Josh G Avatar answered Nov 13 '22 18:11

Josh G


You can set any number of properties using a Xaml Style, and reapply that style - either directly to a separate instance of the control, or as the base for a different style. The latter would allow you to specify your common properties but still, for example, have different visual settings for each control.

So, instead of trying to reproduce this:

<TextBlock Width="100" Height="40" FontSize="10" ClipToBounds="True" />

... define this in a shared resource file:

<Style TargetType="TextBlock" x:Key="myStyle">
    <Setter Property="Width" Value="100" />
    <Setter Property="Height" Value="40" />
    <Setter Property="FontSize" Value="10" />
    <Setter Property="ClipToBounds" Value="True" />
</Style>

... and then use this in markup:

<TextBlock Style="{StaticResource myStyle}" />

The same principle applies to any control and any set of properties.

like image 23
Dan Puzey Avatar answered Nov 13 '22 18:11

Dan Puzey