2017-09-28 64 views
0

我有一個自定義窗口類,增加了一些行爲的窗口工作綁定到嵌套的用戶控件的父:在設計時和運行時

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); 
    } 
} 

ContentPresenterContent="{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}"

在這一點上我有兩個問題:

  1. 是否有可能在該CustomUserControl.xaml設計師設計時的數據,而在MainWindow.xaml設計和運行過程中出現了對父母的真實數據? (我在測試過程中注意到CustomUserControlParent屬性在它的構造函數中爲null,所以我無法獲得父窗口的數據(如果存在的話)。)
  2. 實際上是否有一種方法來「注入」不需要手動將它添加到窗口中就可以將CustomUserControl添加到窗口中?我試圖替換CustomWindow構造函數中的Content屬性,但它在某個點被替換,並且從不可見。

回答

1

有沒有真正「注入」的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 data context for design time and run time

+1

我把你的想法用'ControlTemplate'更進一步,因爲我偶然發現[本條](https://blog.magnusmontin.net/2013/03/16/how-to-create-a-custom-window -in-WPF /)。相反,我只是把我的'CustomUserControl',並能夠在設置它的'DataContext'筆者使用模板中的自定義鑲邊的'OnApplyTemplate'覆蓋 - 這正是我一直在尋找談論時「注射」。非常感謝您的建議! –