【发布时间】:2016-03-30 07:38:34
【问题描述】:
我们正在尝试使用 VS 2013 和 WPF 编写一个 WPF 窗口设计器应用程序。 在此应用程序中,控件在运行时创建并放置在 Canvas 上;包括属性和绑定的设置。 在完成这样的动态 WPF 窗口后,我们希望将 Canvas 及其子控件序列化为 XML 文件。 为此,我们使用这样的 XamlWriter:
public string SerializeControlToXaml(FrameworkElement control)
{
StringBuilder outstr = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
XamlDesignerSerializationManager dsm =
new XamlDesignerSerializationManager(XmlWriter.Create(outstr, settings));
dsm.XamlWriterMode = XamlWriterMode.Expression;
System.Windows.Markup.XamlWriter.Save(control, dsm);
string xaml = outstr.ToString();
return xaml;
}
在我们的例子中,“control”参数包含 Canvas 面板,它是所有通过代码隐藏创建的控件的父控件。 我们正在创建绑定到 SelectedItem 和 DataGrid 列的文本框。
private void CreateTextboxes()
{
CreateTextbox("firstname", _datagridname, "SelectedItem.vorname", 220, 10);
CreateTextbox("familyname", _datagridname, "SelectedItem.nachname", 220, 40);
}
private void CreateTextbox(string name, string sourceName, string path, double leftPos, double topPos)
{
TextBox tb = new TextBox();
tb.SetValue(Canvas.LeftProperty, leftPos);
tb.SetValue(Canvas.TopProperty, topPos);
tb.Width = 150;
tb.Name = name;
// Binding to the selected item of the DataGrid.
Binding tbbinding = new Binding();
FrameworkElement sourceElement;
ControlList.TryGetValue(sourceName, out sourceElement);
if (sourceElement != null)
{
tbbinding.Source = sourceElement;
}
tbbinding.Path = new PropertyPath(path);
tb.SetBinding(TextBox.TextProperty, tbbinding);
_canvasPanel.Children.Add(tb);
// The new TextBox is added to the Controllist.
ControlList.Add(name, tb);
}
在我们的示例中,创建 TextBox 并设置其属性和绑定的方法被调用了两次。 最后,窗口中有两个 TextBox,它们绑定到 DataGrid 列“firstname”和“familyname”。
但是当我们序列化父控件时,绑定没有序列化。 我们得到的结果是这样的:
<Canvas Background="#FFF0F8FF" Name="DropInCanvas" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sd="clr-namespace:System.Data;assembly=System.Data" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DataGrid CanUserAddRows="False" AutoGenerateColumns="True" Name="datagrid1" Canvas.Left="20" Canvas.Top="10">
<DataGrid.ItemBindingGroup>
<BindingGroup Name="{x:Null}" NotifyOnValidationError="False" ValidatesOnNotifyDataError="True" SharesProposedValues="True" />
</DataGrid.ItemBindingGroup>
<sd:DataRowView />
<sd:DataRowView />
<sd:DataRowView />
<sd:DataRowView />
</DataGrid>
<TextBox Name="firstname" Width="150" Canvas.Left="220" Canvas.Top="10" xml:space="preserve"></TextBox>
<TextBox Name="familyname" Width="150" Canvas.Left="220" Canvas.Top="40" xml:space="preserve"></TextBox>
</Canvas>
有人知道为什么吗?
提前致谢!
帕特里克
【问题讨论】: