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

标签 c# wpf xaml clone uielement

我正在尝试使用具有 StyleUIElement 和/或 FrameworkElement 加载 GridDataTrigger

以下是按预期工作的简单 native 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>

当我将相同的文本保存到一个文件并使用 XAML 将其动态加载到 WindowViewbox 时,它也有效,如下所示:

<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>

但是,如果我尝试从一个 Grid/container 到一个新的,样式不再有效。以下是我目前加载和克隆它们的各种方式:

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;
    }
}

通过 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>

虽然我可以看到它重新格式化了 Style,但我不明白为什么当我用克隆设置 Viewbox.Child 时它不再起作用。更令人困惑的是,然后加载克隆的保存文件就可以了。以下是所有四个( native 、动态、克隆、保存的克隆重新加载)的样子:

4 Examples

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

最佳答案

Rectangle 上的StyleCheckBox 触发。因此,Clone() 将无法单独加载子元素。要同时加载它们,请克隆它们的父级,即 Grid 本身。我重现了您的问题,这对我有用:

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

  Grid CloneXaml = (Grid)Clone(NativeXaml);
  CloneViewbox.Child = CloneXaml;

关于c# - 为什么克隆的 UIElement 或 FrameworkElement 的样式丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57129708/

相关文章:

c# - Mono GC max-heap-size 没有记录。在生产中使用安全吗?

c# - 在 WPF 应用程序中应用 MVVM 模式

C# 将可枚举转换为接口(interface)

c# - Winforms ToolTip 获取和更改所有分配的工具提示

c# - 使用 RazorEngine 时如何输出原始 html(不是来自 MVC)

xaml - 如何在xaml中添加Event事件处理程序?

c# - 使用绑定(bind)作为 ConverterParameter

c# - 如何将 StackPanel 绑定(bind)到非 ObservableCollection?

c# - 主线程的 SynchronizationContext.Current 如何在 Windows 窗体应用程序中变为 null?

c# - 使用 wpf 将 dll 合并为单个 .exe