【问题标题】:Bind UiElement DataContext after loading dynamically with XamlReader.Load(...)使用 XamlReader.Load(...) 动态加载后绑定 UiElement DataContext
【发布时间】: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


【解决方案1】:

许多属性的默认模式是 OneWay。您是否尝试过将其设置为这样的两种方式?

try
{
    this.PrintPreview.Child = GetLabelPreviewControl(labelPath);
    Binding previewBinding = new Binding();
    previewBinding.Source = this.PrintPreview.DataContext;
    previewBinding.Mode = BindingMode.TwoWay; //Set the binding to Two-Way mode
    (this.PrintPreview.Child as FrameworkElement).SetBinding(FrameworkElement.DataContextProperty, previewBinding);
}
catch (Exception ex)
{
    // Handle Exception Stuff here...
}

【讨论】:

  • 如果绑定目标会改变绑定属性,你只需要双向绑定,这里不会发生这种情况。
【解决方案2】:

您不需要 Binding,因为 DataContext 默认情况下由 Property Value Inheritance 从父元素继承。

所以只需删除它:

try
{
    PrintPreview.Child = GetLabelPreviewControl(labelPath);
}
catch (Exception ex)
{
    // Handle Exception Stuff here...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-19
    • 2010-11-03
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    相关资源
    最近更新 更多