为什么克隆的UIElement或FrameworkElement的样式丢失

cod*_*der 7 c# wpf xaml clone uielement

我试图加载GridUIElementS和/或FrameworkElement该含有S StyleDataTrigger秒。

以下是一个简单的本机XAML,它可以按预期工作;在3个状态之间切换复选框可为矩形提供三种不同的样式(请参见底部的图像)。

<Grid
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:XamlVsLoad"
    mc:Ignorable="d"
    Height="450" Width="800">
    <CheckBox Name="MyCheck" IsChecked="True" Content="Checkbox" IsThreeState="True" Margin="10,10,0,0" Width="200"/>
    <Rectangle Height="100" Width="100" StrokeThickness="5" Margin="10,50,100,100">
        <Rectangle.Style>
            <Style TargetType="Rectangle">
                <Setter Property="Fill" Value="White"/>
                <Setter Property="Stroke" Value="Black"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=MyCheck, Path=IsChecked}" Value="True" >
                        <Setter Property="Fill" Value="Orange"/>
                        <Setter Property="Stroke" Value="Blue"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding ElementName=MyCheck, Path=IsChecked}" Value="False" >
                        <Setter Property="Fill" Value="Blue"/>
                        <Setter Property="Stroke" Value="Orange"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Rectangle.Style>
    </Rectangle>
</Grid>
Run Code Online (Sandbox Code Playgroud)

它也可以当我相同的文本保存到一个文件和动态加载到WindowViewbox与XAML这样S:

<Grid.ColumnDefinitions>
    <ColumnDefinition Width="100"/>
    <ColumnDefinition Width="100"/>
    <ColumnDefinition Width="100"/>
    <ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<DockPanel Grid.Column="0">
    <DockPanel>
        <Label Content="Native" DockPanel.Dock="Top" HorizontalAlignment="Center"  Margin="10,10,10,10" />
        <Viewbox Name="NativeViewbox" Height="auto" Width="200" DockPanel.Dock="Top"/>
           <!-- Native Grid Omitted for brevity 3 uniquely named checkboxes -->
        </Viewbox>
</DockPanel>
<DockPanel Grid.Column="1">
    <DockPanel>
        <Label Content="Dynamic" DockPanel.Dock="Top"  HorizontalAlignment="Center"  Margin="10,10,10,10" />
        <Viewbox Name="DynamicViewbox" Height="auto" Width="200" DockPanel.Dock="Top"/>
    </DockPanel>
</DockPanel>
<DockPanel Grid.Column="2">
    <DockPanel>
        <Label Content="Clone" DockPanel.Dock="Top" HorizontalAlignment="Center"  Margin="10,10,10,10" />
        <Viewbox Name="CloneViewbox" Height="auto" Width="200" DockPanel.Dock="Top" />
    </DockPanel>
</DockPanel>
<DockPanel Grid.Column="3">
    <DockPanel>
        <Label Content="Saved" DockPanel.Dock="Top" HorizontalAlignment="Center"  Margin="10,10,10,10" />
        <Viewbox Name="SavedViewbox" Height="auto" Width="200" DockPanel.Dock="Top"/>
    </DockPanel>
</DockPanel>
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试将FrameworkElements/ UIElements从一个Grid/容器复制/克隆/深复制(我尝试了几种不同的方法),则该样式不再起作用。以下是我目前加载和克隆它们的各种方法:

public partial class ReadCopy : Window {
    public ReadCopy() {
        InitializeComponent();
        // test the dynamic load
        Grid NativeXaml = ReadGrid("C:\\XamlFiles\\LoadXaml.xaml");
        DynamicViewbox.Child = NativeXaml; // honors style

        // test the Clone load
        Grid CloneXaml = new Grid();
        foreach (FrameworkElement fe in NativeXaml.Children) CloneXaml.Children.Add(Clone(fe));
        CloneViewbox.Child = CloneXaml;    // doesn't honor style

        // test the save Clone and then load
        StringBuilder outstr = new StringBuilder();
        XmlWriterSettings settings = new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true, IndentChars = "  ", NewLineChars = "\r\n", NewLineHandling = NewLineHandling.Replace };
        XamlDesignerSerializationManager dsm = new XamlDesignerSerializationManager(XmlWriter.Create(outstr, settings)) { XamlWriterMode = XamlWriterMode.Expression };
        XamlWriter.Save(CloneXaml, dsm);
        File.WriteAllText("C:\\XamlFiles\\SavedXaml.xaml", outstr.ToString());

        Grid SavedXaml = ReadGrid("C:\\XamlFiles\\SavedXaml.xaml");
        SavedViewbox.Child = SavedXaml;    // honors style and triggers again...
    }

    public Grid ReadGrid(string fn) {
        FileStream fs = new FileStream(fn, FileMode.Open);
        return XamlReader.Load(fs) as Grid;
    }

    public FrameworkElement Clone(FrameworkElement it) {
        FrameworkElement clone;
        using (var stream = new MemoryStream())  {
            XamlWriter.Save(it, stream);
            stream.Seek(0, SeekOrigin.Begin);
            clone = (FrameworkElement)XamlReader.Load(stream);
        }
        clone.Style = it.Style; // setting it or not has no effect
        return clone;
    }
}
Run Code Online (Sandbox Code Playgroud)

通过XamlWriter.Save开始的简单示例网格的克隆XAML的输出:

<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <CheckBox IsChecked="True" IsThreeState="True" Style="{x:Null}" Name="MyCheck" Width="200" Margin="10,10,0,0">Checkbox</CheckBox>
  <Rectangle StrokeThickness="5" Width="100" Height="100" Margin="10,50,100,100">
    <Rectangle.Style>
      <Style TargetType="Rectangle">
        <Style.Triggers>
          <DataTrigger Binding="{Binding Path=IsChecked, ElementName=MyCheck}" Value="True">
            <Setter Property="Shape.Fill">
              <Setter.Value>
                <SolidColorBrush>#FFFFA500</SolidColorBrush>
              </Setter.Value>
            </Setter>
            <Setter Property="Shape.Stroke">
              <Setter.Value>
                <SolidColorBrush>#FF0000FF</SolidColorBrush>
              </Setter.Value>
            </Setter>
          </DataTrigger>
          <DataTrigger Binding="{Binding Path=IsChecked, ElementName=MyCheck}" Value="False">
            <Setter Property="Shape.Fill">
              <Setter.Value>
                <SolidColorBrush>#FF0000FF</SolidColorBrush>
              </Setter.Value>
            </Setter>
            <Setter Property="Shape.Stroke">
              <Setter.Value>
                <SolidColorBrush>#FFFFA500</SolidColorBrush>
              </Setter.Value>
            </Setter>
          </DataTrigger>
        </Style.Triggers>
        <Style.Resources>
          <ResourceDictionary />
        </Style.Resources>
        <Setter Property="Shape.Fill">
          <Setter.Value>
            <SolidColorBrush>#FFFFFFFF</SolidColorBrush>
          </Setter.Value>
        </Setter>
        <Setter Property="Shape.Stroke">
          <Setter.Value>
            <SolidColorBrush>#FF000000</SolidColorBrush>
          </Setter.Value>
        </Setter>
      </Style>
    </Rectangle.Style>
  </Rectangle>
</Grid>
Run Code Online (Sandbox Code Playgroud)

虽然我可以看到它重新格式化了Style,但我不明白为什么在设置Viewbox.Child克隆时它不再起作用。更令人困惑的是,加载克隆的已保存文件就可以了。这是全部四个(本机,动态,克隆,已保存的克隆重载)的外观:

4个例子

谁能解释如何通过复制/克隆正确保留样式?

小智 5

StyleRectangle被触发CheckBox。因此,Clone()将无法单独加载子元素。要同时加载它们,请克隆其父级Grid本身。我转载了您的问题,这对我有用:

  Grid NativeXaml = ReadGrid();
  DynamicViewbox.Child = NativeXaml;

  Grid CloneXaml = (Grid)Clone(NativeXaml);
  CloneViewbox.Child = CloneXaml;
Run Code Online (Sandbox Code Playgroud)