[英]Binding to Parent of nested UserControl during design-time and runtime
我正在使用自定義窗口類,該類向窗口添加一些行為:
class CustomWindow : Window {
public CustomWindow() {
// ...
}
}
我當前的MainWindow.xaml
看起來像預期的那樣:
<local:CustomWindow ...>
<!-- ... -->
</local:CustomWindow>
現在,我想將窗口的內容托管在一個自定義容器中,該容器應該是窗口本身的根元素,但是我首先要實現容器的自動創建。 因此,我正在手動執行我現在想使用“硬編碼”控件進行自動化的操作:
<local:CustomWindow ...>
<local:CustomUserControl>
<!-- ... -->
</local:CustomUserControl>
</local:CustomWindow>
為了顯示通過XAML添加的內容,我引入了一個Content屬性,如下所示:
[ContentProperty("InnerContent")]
public partial class CustomUserControl : UserControl
{
public static readonly DependencyProperty InnerContentProperty =
DependencyProperty.Register("InnerContent", typeof(object),
typeof(CustomUserControl));
public object InnerContent
{
get => GetValue(InnerContentProperty);
set => SetValue(InnerContentProperty, value);
}
}
以及XAML文件中的ContentPresenter
和Content="{Binding Path=InnerContent, ElementName=customUserControl}"
。 在這一點上,我正在努力實現一些其他的綁定。 我有一個TextBlock,現在我想綁定到父窗口的屬性。 層次結構如下所示:
CustomWindow
|- CustomUserControl
|- ...
|- TextBlock
當我將Text
屬性設置為{Binding Path=Title, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:CustomWindow}}}
時,這當然會在運行時起作用,但在窗口設計器的設計時不會起作用。 當然,我不能將這種綁定與我已經引入的d:DataContext="{d:DesignInstance local:FakeCustomUserControlData, IsDesignTimeCreatable=True}"
這樣的設計DataContext
一起使用。
在這一點上,我有兩個問題:
CustomUserControl.xaml
設計器中擁有設計時數據,而在MainWindow.xaml
設計器中以及運行時,我可以獲取有關父級的真實數據? (在測試過程中,我注意到CustomUserControl
的Parent
屬性在其構造函數期間為null,因此,如果存在父窗口,則我無法獲取它的數據。) CustomUserControl
“注入”到窗口中,而無需手動將其添加到窗口中? 我試圖替換CustomWindow
構造函數中的Content
屬性,但是在某些時候它被替換了並且從不可見。 實際上有沒有一種方法可以將
CustomUserControl
“注入”到窗口中,而無需手動將其添加到窗口中?
為包含UserControl
的窗口定義一個自定義模板:
<Window x:Class="WpfApp1.Window1"
...>
<Window.Template>
<ControlTemplate TargetType="Window">
<AdornerDecorator>
<local:CustomUserControl Background="White">
<ContentPresenter />
</local:CustomUserControl>
</AdornerDecorator>
</ControlTemplate>
</Window.Template>
<Grid>
<TextBlock>the content...</TextBlock>
</Grid>
</Window>
是否可以在CustomUserControl.xaml設計器中擁有設計時數據,而在
MainWindow.xaml
設計器中以及運行時,我可以獲取有關父級的真實數據?
您應該能夠為UserControl
: WPF數據上下文設置設計時間和運行時間的設計時間數據上下文 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.