为什么RelativeSource绑定表现不一致?

时间:2018-02-15 17:16:08

标签: c# wpf

注意:我知道我应该使用{Binding RelativeSource={RelativeSource TemplatedParent}}来解决提出的问题,但我想知道 出现问题的原因。

我有一个自定义控件CustomTextControlControlTemplate我使用RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:CustomTextControl}},当我在Window内显示时,所有内容都会按预期显示。

但是当我尝试使用PrintVisual System.Windows.Controls.PrintDialog方法打印相同的控件时,未正确评估绑定。

示例:

public class CustomTextControl : ContentControl
{
    static CustomTextControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomTextControl), new FrameworkPropertyMetadata(typeof(CustomTextControl)));
    }
}

Generic.xaml(local引用我的项目命名空间的xmlns:local定义):

<Style TargetType="{x:Type local:CustomTextControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:CustomTextControl}">
                <TextBlock
                    Background="Red"
                    Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:CustomTextControl}},Path=Content}"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

MainWindow内容:

<Grid>
    <local:CustomTextControl Content="My text to be displayed" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="10"/>

    <Button Content="PrintTest" Click="Button_Click" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="10,100,10,10"/>
</Grid>

控件以红色背景和指定的文本内容显示。

MainWindow代码背后:

private void Button_Click(object sender, RoutedEventArgs args)
{
    var e = new CustomTextControl();

    e.Content = "My text to be printed";
    e.Margin = new Thickness(30);
    e.UpdateLayout();

    var print = new PrintDialog();

    if (print.ShowDialog() != true) return;

    var w = print.PrintTicket.PageMediaSize.Width ?? 600;
    var h = print.PrintTicket.PageMediaSize.Height ?? 1000;
    e.Measure(new Size(w, h));
    e.Arrange(new Rect(0, 0, w, h));

    print.PrintVisual(e, "Test Printing");
}

如您所见,我创建了一个单独的控件,它与主窗口内的控件非常相似。

结果:打印的文档包含红色背景,但不包含文本内容。

我的问题:为什么文本内容会显示在窗口中而不会显示在打印文档中?

更新

如果我在MessageBox.Show("Test");之前放置print.PrintVisual(e, "Test Printing");,那么打印的文档会有红色背景,因此这是某种工作/时间问题。

我能够通过在打印语句中使用Dispatcher.BeginInvoke来解析我的具体示例,但是对于涉及数据绑定CheckBox的一些修改示例,这还不够,即使使用{{1} }。

1 个答案:

答案 0 :(得分:0)

我认为会发生这种情况,因为您的控件不在视觉树中。 RelativeSource绑定在当前控件的父级中搜索。 您可以尝试在模板定义中将 RelativeSource 替换为 TemplateBinding

尝试使用

AccountNO

而不是:

Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:CustomTextControl}},Path=Content}"/>
相关问题