【发布时间】:2009-08-09 20:30:42
【问题描述】:
我想生成一些将包含在 WPF 应用程序中的库代码。图书馆可能会弹出一个窗口,视情况而定。我可以在 XAML 中定义窗口,但我想将 XAML 视为模板。在运行时,在创建窗口以便显示时,我想用运行时定义的值替换 Xaml 模板中的某些标记。
我想做的是这样的:
public partial class DynamicXamlWindow : Window
{
Button btnUpdate = null;
public DynamicXamlWindow()
{
string s = XamlTemplate;
// replace some things in the XamlTemplate here
Window root = System.Windows.Markup.XamlReader.Load(...);
Object _root = this.InitializeFromXaml(new StringReader(s).ReadToEnd()); //??
btnUpdate = // ???
//InitializeComponent();
}
XamlTemplate 字符串如下所示:
private string XamlTemplate = @"
<Window x:Class='@@CLASS'
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
Title='@@TITLE'
Height='346' Width='380'>
<Grid>
...
我已经看到了在 XAML 中定义按钮或部分并动态加载的示例。但这不是按钮或部分。 XamlTemplate 为实际的 Window 提供 XAML。
这是否可以通过 InitializeFromXaml 或 XamlReader.Load 实现?如果有,怎么做?
然后我可以检索在 XAML 中定义的控件,例如上面代码片段中的 btnUpdate。如何?
【问题讨论】: