【问题标题】:How to show XAML as text in WPF application如何在 WPF 应用程序中将 XAML 显示为文本
【发布时间】:2015-02-23 10:12:57
【问题描述】:

我们正在更新包含自定义样式控件的库 WPF 应用程序。设计是有一个切换来显示这些自定义控件背后的 XAML,以便于参考和新同事的指南。

我目前实现这一点的方式是创建两个 .xaml 文件,一个仅包含控件,一个包含控件,另一个包含用于实现这些控件的 XAML 编码的文本块。

这不是一个容易维护的东西,因为引号、>、

<TextBlock Visibility="Collapsed" Margin="5" Text="&lt;controls:AutoCompleteTagBox&#10;
           Name=&quot;AutoCompleteTagBoxWithStrings&quot;&#10;
           Margin=&quot;5&quot;&#10;
           ItemsSource=&quot;{Binding Names}&quot;&#10;
           FilterMode=&quot;Contains&quot; /&gt;&#10;
           &lt;ListBox&#10;
           ItemsSource=&quot;{Binding ElementName=AutoCompleteTagBoxWithStrings, Path=SelectedItems}&quot;&#10;
           Grid.Column=&quot;1&quot;&#10;
           BorderBrush=&quot;{StaticResource Blue}&quot; BorderThickness=&quot;1&quot; /&gt;"/>

如您所见,它看起来不太好,一旦您更新其中一个控件,您现在需要在三个地方更改 XAML。

下一步就是绑定 TextBlock 可见性并将其从“折叠”切换为“可见”。但我想知道是否有一种方法可以在文本块中显示 XAML 而无需手写字符串。

提前感谢您的建议!

【问题讨论】:

  • 你试过用XamlWriter.Save有没有例子here
  • 我试过了,但是由于 XamlWriter 无法序列化泛型类型,并且大多数变通方法都试图让我重新编写我们所有的控件类。这不是我们想做的只是为了展示 XAML。
  • 好的。我刚刚查看了this post,公平地说,如果你只是为你的Binding 使用装饰器,这似乎不是很多工作,除非它当然不是那么简单?
  • 是的,就是这样!感谢您的帮助!

标签: c# wpf xaml


【解决方案1】:

根据 XAMIMAX 的评论,您可以使用简单的转换器将 xaml 保存为使用 XamlWriter 的字符串,并为简洁起见去除 xmlns 命名空间。

public class XamlConverter : IValueConverter
{
    public readonly Regex xmlnsRegex = new Regex("xmlns=\".+\"");

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var source = value as FrameworkElement;
        if (source != null)
        {
            //Save xaml and strip xmlns namespaces
            var xaml = xmlnsRegex.Replace(System.Windows.Markup.XamlWriter.Save(source), "");

            return xaml;
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

示例用法

<StackPanel>
    <StackPanel.Resources>
        <converters:XamlConverter x:Key="Converter_Xaml"/>
    </StackPanel.Resources>
    <Button x:Name="SourceButton" Content="Click Me" Margin="10"/>
    <TextBlock Text="{Binding ElementName=SourceButton, Converter={StaticResource Converter_Xaml}}" TextWrapping="Wrap"/>
</StackPanel>

【讨论】:

  • 减去 XAMLWriter 的限制后,我得到了 XANIMAX 的额外提示。谢谢!
猜你喜欢
  • 2010-11-18
  • 2016-12-17
  • 2018-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-04
  • 2016-08-23
相关资源
最近更新 更多