【发布时间】:2016-05-12 09:32:56
【问题描述】:
猜猜这最终很容易,我只是在思考障碍或其他什么,但这里是:
这基本上是一些运输标签的打印预览。由于目标是能够使用不同的标签设计,我目前正在使用XamlReader.Load() 从 XAML 文件中动态加载预览标签模板(以便可以对其进行修改而无需明显重新编译程序)。
public UIElement GetLabelPreviewControl(string path)
{
FileStream stream = new FileStream(path, FileMode.Open);
UIElement shippingLabel = (UIElement)XamlReader.Load(stream);
stream.Close();
return shippingLabel;
}
加载的元素基本上是一个画布
<Canvas Width="576" Height="384" Background="White"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Canvas.Resources>
<!-- Formatting Stuff -->
</Canvas.Resources>
<!-- Layout template -->
<TextBlock Margin="30 222 0 0" Text="{Binding Path=Name1}" />
<!-- More bound elements -->
</Canvas>
即插入到边框控件中:
<Border Grid.Column="1" Name="PrintPreview" Width="596" Height="404" Background="LightGray">
</Border>
显然我很懒,不想在每次父级上的 DataContext 更改时在预览中手动更新 DataContext(因为它也是错误的来源),但我宁愿在后面的代码中创建一个绑定:
try
{
this.PrintPreview.Child = GetLabelPreviewControl(labelPath);
Binding previewBinding = new Binding();
previewBinding.Source = this.PrintPreview.DataContext;
(this.PrintPreview.Child as FrameworkElement).SetBinding(FrameworkElement.DataContextProperty, previewBinding);
}
catch (Exception ex)
{
// Handle Exception Stuff here...
}
在加载模板时,它可以完美运行。绑定会更新所有预览的数据字段。
当父级上的 DataContext 更改时,就会出现问题。然后此更改不会反映在加载的预览中,但上下文只是保持绑定到旧对象......我的绑定表达式有问题还是我在这里缺少什么?
【问题讨论】:
-
您根本不需要 DataContext 绑定,因为默认情况下 DataContext 是由 Property Value Inheritance 从父元素继承而来的。
-
谢谢...这是错误的。我不知何故想到我必须在运行时加载
UIElement后手动绑定DataContext。
标签: c# wpf binding code-behind