2009-02-19 51 views
5

如何在WPF中創建公共窗口外觀?我不是在談論窗體的造型,我的意思是有一個有邊框,網格和其他東西的窗口。在WPF中創建公共窗口外觀

謝謝。

+0

你能解釋多一點..你想要一個預定義內容的窗口......就像ASP中的主頁面?還是我在錯誤的軌道上? – Gishu 2009-02-19 17:04:57

回答

0

我最終做的是創建一個基類,創建我想在每個窗口中使用的UI代碼。這使我可以爲控件設置事件並在基類中擁有事件訂閱。如果有更好的方法來做到這一點,比如使用xaml,我想知道。

public WindowBase() 
{ 
    Initialized += WindowBase_Initialized; 
} 

private void WindowBase_Initialized(object sender, EventArgs e) 
{ 
    Border border = new Border(); 
    border.SetResourceReference(Control.StyleProperty, "WindowBorder"); 

    border.Child = new ContentPresenter { Content = this.Content}; 

    this.Content = border; 
} 
5

您可以爲窗口創建ControlTemplate。這是一個非常基本的例子,它有一些控件和觸發器。您可以輕鬆添加更多元素以使其符合您的需求。

<ControlTemplate x:Key="MyWindowTemplate" TargetType="{x:Type Window}"> 
     <Border x:Name="WindowBorder" Style="{DynamicResource WindowBorderStyle}"> 
     <Grid> 
      <Border Margin="4,4,4,4" Padding="0,0,0,0" x:Name="MarginBorder"> 
       <AdornerDecorator> 
        <ContentPresenter/> 
       </AdornerDecorator> 
      </Border> 
      <ResizeGrip Visibility="Collapsed" IsTabStop="false" HorizontalAlignment="Right" x:Name="WindowResizeGrip" 
        VerticalAlignment="Bottom" /> 
     </Grid> 
     </Border> 
     <ControlTemplate.Triggers> 
     <MultiTrigger> 
      <MultiTrigger.Conditions> 
       <Condition Property="ResizeMode" Value="CanResizeWithGrip"/> 
       <Condition Property="WindowState" Value="Normal"/> 
      </MultiTrigger.Conditions> 
      <Setter Property="Visibility" TargetName="WindowResizeGrip" Value="Visible"/> 
      <Setter Property="Margin" TargetName="MarginBorder" Value="4,4,4,20" /> 
     </MultiTrigger> 
     <Trigger Property="WindowState" Value="Maximized"> 
      <Setter Property="CornerRadius" TargetName="WindowBorder" Value="0,0,0,0"/> 
     </Trigger> 
     </ControlTemplate.Triggers> 
    </ControlTemplate> 

您可以通過設置窗口的模板屬性中使用控件模板:

Template="{StaticResource MyWindowTemplate}" 

你會想結合這樣的風格使用:

<Style x:Key="MyWindowStyle" TargetType="{x:Type Window}"> 
     <Setter Property="AllowsTransparency" Value="False" /> 
     <Setter Property="WindowStyle" Value="SingleBorderWindow" /> 
     <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}"/> 
     <Setter Property="Background" Value="Transparent" /> 
     <Setter Property="ShowInTaskbar" Value="False" /> 
     <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type Window}"> 
       <Border> 
        <AdornerDecorator> 
        <ContentPresenter/> 
        </AdornerDecorator> 
       </Border> 
      </ControlTemplate> 
     </Setter.Value> 
     </Setter> 
    </Style> 

而且像這樣設置窗口上的樣式:

Style="{StaticResource MyWindowStyle}" 
+0

這很好。我現在唯一的問題是我在ControlTemplate代碼中有一些事件。如果我希望所有窗口都使用該模板,那麼我需要將該資源放入不同的文件中。當我這樣做時,事件不再起作用。 – 2009-02-20 19:59:50