如何通过 WPF 中的 c# 代码隐藏编写逐字 XAML 代码
本文关键字:代码 XAML 隐藏 WPF 中的 何通过 | 更新日期: 2023-09-27 18:34:56
我想在运行时将纯 XAML 代码添加到我的 xaml 元素中。有谁知道该怎么做?谢谢。我想做这样的事情:myGrid.innerXAML = stringXAMLcode这将导致<grid name="myGrid">newgeneratedcodehere</grid>
在PHP中,你可以直接将逐字HTML代码打印到HTML文件中。这在 c# 中可能吗?如果没有,任何人都可以建议解决方法吗?谢谢!

有一些方法可以完成您在此处要求的操作,如本 CodeProject 文章中所述:
在代码中创建 WPF 数据模板:正确的方法
但是,大多数时候,您真的不需要它进行日常操作。
如果您正在使用 WPF,您确实需要抛弃其他框架的传统方法,并采用 WPF 心态。
与 XAML 的 WPF 实现相比,HTML(4、5 或其他(看起来像一个荒谬的笑话,因此您在 HTML 中可能习惯的所有可怕的黑客在 WPF 中都是完全不需要的,因为后者具有许多内置功能,可帮助您以非常干净的方式实现高级 UI 功能。
WPF 在很大程度上基于数据绑定,并促进 UI 和数据之间明确且定义良好的分离。
例如,当您希望使用名为 DataTemplates 的 WPF 功能根据数据"显示不同的 UI 片段"时,
您将执行以下操作:XAML:
<Window x:Class="MyWindow"
...
xmlns:local="clr-namespace:MyNamespace">
<Window.Resources>
<DataTemplate DataType="{x:Type local:Person}">
<!-- this is the UI that will be used for Person -->
<TextBox Text="{Binding LastName}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:Product}">
<!-- this is the UI that will be used for Product -->
<Grid Background="Red">
<TextBox Text="{Binding ProductName}"/>
</Grid>
</DataTemplate>
</Window.Resources>
<Grid>
<!-- the UI defined above will be placed here, inside the ContentPresenter -->
<ContentPresenter Content="{Binding Data}"/>
</Grid>
</Window>
代码隐藏:
public class MyWindow
{
public MyWindow()
{
InitializeComponent();
DataContext = new MyViewModel();
}
}
视图模型:
public class MyViewModel
{
public DataObjectBase Data {get;set;} //INotifyPropertyChanged is required
}
数据模型:
public class DataObjectBase
{
//.. Whatever members you want to have in the base class for entities.
}
public class Person: DataObjectBase
{
public string LastName {get;set;}
}
public class Product: DataObjectBase
{
public string ProductName {get;set;}
}
请注意我是如何谈论我的Data和Business Objects,而不是担心任何操纵 UI 的黑客。
另请注意,在将由 Visual Studio 编译的 XAML 文件中定义 DataTemplates 如何让我对我的 XAML 进行编译时检查,而不是将它们放在过程代码的string中,当然,过程代码没有任何一致性检查。
我强烈建议您阅读Rachel的答案(上面链接(和相关博客文章。
WPF 岩石
你为什么不准确地添加你想要的元素?像这样:
StackPanel p = new StackPanel();
Grid g = new Grid();
TextBlock bl = new TextBlock();
bl.Text = "This is a test";
g.addChildren(bl);
p.addChildren(g);
您可以对 XAML 中存在的所有元素执行此操作。
问候
XamlReader创建可设置为内容控件或布局容器子级的UIElement:
string myXamlString = "YOUR XAML THAT NEEDED TO BE INSERTED";
XmlReader myXmlReader = XmlReader.Create(myXamlString);
UIElement myElement = (UIElement)XamlReader.Load(myXmlReader);
myGrid.Children.Add(myElement );