亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

解析代碼中的 XAML 樣式并加載自定義控件

解析代碼中的 XAML 樣式并加載自定義控件

C#
Cats萌萌 2021-06-03 15:11:39
我有一個使用 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)));        }    }}然后用XamlParser解析它并將其加載到customcontrol1那可能嗎 ?謝謝
查看完整描述

1 回答

?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

答案是 :

  1. 創建自定義控件的公共版本:

    public CustomControl1() { }

  2. 創建自定義控件的公共版本:

    public CustomControl1(){
        ResourceDictionary Parse_Resource = XamlReader.Parse(code_xaml) as ResourceDictionary;    
        this.Resources = Parse_Resource;
        }

解決了:D


查看完整回答
反對 回復 2021-06-05
  • 1 回答
  • 0 關注
  • 165 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號