我有一個自定義窗口類,增加了一些行爲的窗口工作綁定到嵌套的用戶控件的父:在設計時和運行時
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);
}
}
和ContentPresenter
與Content="{Binding Path=InnerContent, ElementName=customUserControl}"
在XAML文件中。在這一點上,我正在努力想要實現一些更進一步的綁定。我有一個TextBlock,我想要綁定到父窗口的屬性。層次結構如下所示:
CustomWindow
|- CustomUserControl
|- ...
|- TextBlock
當我在窗口設計師設計時Text
屬性設置爲{Binding Path=Title, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:CustomWindow}}}
當然運行在此工作,但不是。當然,我不能使用這種綁定與我已經介紹過的設計DataContext
這樣的d:DataContext="{d:DesignInstance local:FakeCustomUserControlData, IsDesignTimeCreatable=True}"
。
在這一點上我有兩個問題:
- 是否有可能在該
CustomUserControl.xaml
設計師設計時的數據,而在MainWindow.xaml
設計和運行過程中出現了對父母的真實數據? (我在測試過程中注意到CustomUserControl
的Parent
屬性在它的構造函數中爲null,所以我無法獲得父窗口的數據(如果存在的話)。) - 實際上是否有一種方法來「注入」不需要手動將它添加到窗口中就可以將
CustomUserControl
添加到窗口中?我試圖替換CustomWindow
構造函數中的Content
屬性,但它在某個點被替換,並且從不可見。
我把你的想法用'ControlTemplate'更進一步,因爲我偶然發現[本條](https://blog.magnusmontin.net/2013/03/16/how-to-create-a-custom-window -in-WPF /)。相反,我只是把我的'CustomUserControl',並能夠在設置它的'DataContext'筆者使用模板中的自定義鑲邊的'OnApplyTemplate'覆蓋 - 這正是我一直在尋找談論時「注射」。非常感謝您的建議! –