在代码中解析XAML样式并加载自定义控件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在代码中解析XAML样式并加载自定义控件相关的知识,希望对你有一定的参考价值。
我有一个使用Roslyn解析C#代码的c ++程序。我需要将我的样式和自定义控件转换为“代码隐藏”。
例如,我有一个简单的自定义控件包含一个按钮。
XAML风格:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CUSTOM_LIBRARY_PARSE">
<Style TargetType="{x:Type local:CustomControl1}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl1}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Button Background="#FF487DF0" >
<Label VerticalContentAlignment="Center" HorizontalContentAlignment="Center" OpacityMask="#FFC3C3C3" Content="{Binding text_of_button_Value, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:CustomControl1}}}" />
</Button>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
控制代码:
using System;
using System.Windows;
using System.Windows.Controls;
namespace CUSTOM_LIBRARY_PARSE
{
public class CustomControl1 : Control
{
public static readonly DependencyProperty text_of_button
= DependencyProperty.Register(
"text_of_button_Value",
typeof(string),
typeof(CustomControl1),
new PropertyMetadata(Environment.UserName)
);
public string text_of_button_Value
{
get { return (string)GetValue(text_of_button); }
set { SetValue(text_of_button, value); }
}
static CustomControl1()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
}
}
}
现在,我需要知道如何在代码中嵌入xaml代码作为字符串,如:
string code_xaml = "<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CUSTOM_LIBRARY_PARSE">
<Style TargetType="{x:Type local:CustomControl1}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl1}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Button Background="#FF487DF0" >
<Label VerticalContentAlignment="Center" HorizontalContentAlignment="Center" OpacityMask="#FFC3C3C3" Content="{Binding text_of_button_Value, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:CustomControl1}}}" />
</Button>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
";
然后使用XamlParser解析它并将其加载到customcontrol1
那可能吗 ?谢谢
答案
答案是 :
- 创建自定义控件的公共版本:
public CustomControl1() { }
- 创建自定义控件的公共版本:
public CustomControl1() { ResourceDictionary Parse_Resource = XamlReader.Parse(code_xaml) as ResourceDictionary; this.Resources = Parse_Resource; }
解决了:D
以上是关于在代码中解析XAML样式并加载自定义控件的主要内容,如果未能解决你的问题,请参考以下文章