wpf用xamlReader读取一段string,有没有例子啊?

wrjhkg5c 2012-10-24 11:11:09
尝试了网上很多,都失败了。

例如,下面的例子,连编译都不通过:




StringBuilder sb = new StringBuilder();
sb.Append("<Button Content=\"ok\" Width=\"100\" Height=\"50\"></Button>");
Button btn = System.Windows.Markup.XamlReader.Load(sb.ToString()) as Button;
this.AddChild(btn);














...全文
197 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
china0tech 2012-10-24
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 的回复:]

是的,你的成功了。
不过,我看网上的都是直接输入string参数的,你这里为什么输入的是XmlTextReader参数?

能不能再简单点?


引用 2 楼 的回复:

C# code

using System.IO;
using System.Windows.Markup;
using System.Xml;


namespace xamlreader
……
[/Quote]
你看看
XamlReader.Load的重载参数就明白了。
lhx527099095 2012-10-24
  • 打赏
  • 举报
回复
粗心了 忘记写 xmlns了 sorry
wrjhkg5c 2012-10-24
  • 打赏
  • 举报
回复
这个成功了,最简单的代码了。


[Quote=引用 5 楼 的回复:]

忘记了 加 xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'

string xaml = "<TextBlock xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>Hello World!</TextBlock>";
……
[/Quote]
wrjhkg5c 2012-10-24
  • 打赏
  • 举报
回复
你的代码,编译能通过,但运行的时候崩溃了。



[Quote=引用 3 楼 的回复:]

C# code


string xaml = "<TextBlock >Hello World!</TextBlock>";
UIElement element = XamlReader.Parse(xaml) as UIElement;



用Parse赋值 load是加载文件的
[/Quote]
lhx527099095 2012-10-24
  • 打赏
  • 举报
回复
忘记了 加 xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'

string xaml = "<TextBlock xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>Hello World!</TextBlock>";
TextBlock element = XamlReader.Parse(xaml) as TextBlock;
wrjhkg5c 2012-10-24
  • 打赏
  • 举报
回复
是的,你的成功了。
不过,我看网上的都是直接输入string参数的,你这里为什么输入的是XmlTextReader参数?

能不能再简单点?


[Quote=引用 2 楼 的回复:]

C# code

using System.IO;
using System.Windows.Markup;
using System.Xml;


namespace xamlreader
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWind……
[/Quote]
lhx527099095 2012-10-24
  • 打赏
  • 举报
回复


string xaml = "<TextBlock >Hello World!</TextBlock>";
UIElement element = XamlReader.Parse(xaml) as UIElement;


用Parse赋值 load是加载文件的
china0tech 2012-10-24
  • 打赏
  • 举报
回复

using System.IO;
using System.Windows.Markup;
using System.Xml;


namespace xamlreader
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
LoadXaml();
}

public void LoadXaml()
{

StringBuilder sb = new StringBuilder();
sb.Append("<Button xmlns='http://schemas.microsoft.com/" + "winfx/2006/xaml/presentation'");
sb.Append(" Content='hello' Foreground='Red'>");
sb.Append("</Button>");
StringReader strreader = new StringReader(sb.ToString());
XmlTextReader xmlreader = new XmlTextReader(strreader);
object obj = XamlReader.Load(xmlreader);

Content = obj;

}

}
}


是这样的效果吗?
wrjhkg5c 2012-10-24
  • 打赏
  • 举报
回复
有没有哪位大侠懂的啊?

110,524

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧