2016-02-03 23 views
0

竞猜动态加载后这到底blatently容易,我只是我一记块或东西上,但这里有云:绑定的UIElement的DataContext与XamlReader.Load(...)

这基本上是关于一个打印预览一些运输标签。由于目标是能够使用不同的标签设计,因此我目前使用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发生更改时(因为它也是错误的来源),在预览上手动进行预览,但我宁愿在后面的代码中创建Binding:

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在父级更改时出现问题。然后这个改变并不反映在加载的预览中,但是Context只是保持绑定到旧对象......我的绑定表达式有什么问题,或者我在这里丢失了什么?

+1

你不应该需要DataContext的所有结合,作为DataContext的是默认由[属性值继承(HTTPS父元素继承:// MSDN。 microsoft.com/en-us/library/ms753197(v=vs.100).aspx)。 – Clemens

+0

谢谢......那是错误。我不知何故在脑海中想到,我必须在运行时加载'UIElement'后手动绑定'DataContext'。 – Adwaenyth

回答

1

你不需要绑定,因为DataContext在默认情况下从父元素继承了Property Value Inheritance

所以只是将其删除:

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

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

如果绑定目标会更改绑定属性,则只需要双向绑定即可,这在此处不会发生。 – Clemens