开发者

WPF Create instances of controls defined in xaml

开发者 https://www.devze.com 2023-02-20 02:14 出处:网络
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开发者

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开发者_StackOverflow中文版 the code behind?


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


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.


Have you considered creating the control as a UserControl?


Yes you can by using XamlReader: http://msdn.microsoft.com/en-us/library/system.windows.markup.xamlreader.aspx. Use the static method Load passing a stream containing your xaml markup. You obtain an object that is your control instance.

0

精彩评论

暂无评论...
验证码 换一张
取 消