简体   繁体   中英

WPF Create instances of controls defined in xaml

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?

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.

您是否考虑过将控件创建为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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM