使用 XamlReader.Load(..) 动态加载后绑定 UiElement DataContext

本文关键字:绑定 UiElement DataContext 加载 动态 XamlReader Load 使用 | 更新日期: 2023-09-27 18: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(因为它也是错误的来源(,但我宁愿在代码隐藏中创建绑定:

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...
}

加载模板时,它可以完美运行。绑定将更新预览的所有数据字段。

当父级上的数据上下文发生更改时,就会出现问题。然后,此更改不会反映在加载的预览中,但上下文只是绑定到旧对象...我的绑定表达式是否有问题,或者我在这里还缺少什么?

使用 XamlReader.Load(..) 动态加载后绑定 UiElement DataContext

您不需要绑定,因为默认情况下,DataContext是通过属性值继承从父元素继承的。

所以只需删除它:

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

许多属性的默认模式是 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...
}