[英]Why does RelativeSource Binding behave inconsistent?
注意:我知道我應該使用{Binding RelativeSource={RelativeSource TemplatedParent}}
解決出現的問題,但是我想知道為什么出現該問題。
我有一個帶有ControlTemplate
的自定義控件CustomTextControl
,其中使用了RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:CustomTextControl}}
,當我將其顯示在Window
,一切都按預期顯示。
但是,當我嘗試使用System.Windows.Controls.PrintDialog
的PrintVisual
方法打印相同的控件時,綁定評估不正確。
例:
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
來解決我的特定示例,但是對於涉及Data-Bound CheckBox
的稍加修改的示例,即使使用DispatcherPriority.ApplicationIdle
還是不夠的。
我認為這是因為您的控件不在可視樹中。 RelativeSource綁定在當前控件的父級中搜索。 您可以嘗試在模板定義中用TemplateBinding替換您的RelativeSource 。
嘗試使用
Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:CustomTextControl}},Path=Content}"/>
代替:
Text="{TemplateBinding Content}"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.