我在共享用户控件库中实现了以下控件模板
<ControlTemplate x:Key="WindowTemplate" TargetType="{x:Type Window}">
<Border Name="Frame" Style="{StaticResource WindowBorder}" MouseLeftButtonDown="titleBar_MouseLeftButtonDown">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="*" />
<RowDefinition Height="40"/>
</Grid.RowDefinitions>
<controls:AppHeader Grid.Row="0" x:Name="Appheader" HeaderTitle="{Binding Path=AppTitle}" HeaderImageSource="{Binding Path=ImageSource}" ></controls:AppHeader>
<Border Grid.Row="1" BorderThickness="0,0,0,2" BorderBrush="#FFC1C1C1">
<ContentPresenter />
</Border>
<controls:AppNavigator Grid.Row="2" x:Name="AppNavigator"></controls:AppNavigator>
</Grid>
</Border>
</ControlTemplate>
<Style x:Key="WindowToolStyle" TargetType="Window">
<Setter Property="Height" Value="400"/>
<Setter Property="Width" Value="600"/>
<Setter Property="WindowStyle" Value="None" />
<Setter Property="ResizeMode" Value="NoResize"/>
<Setter Property="Topmost" Value="False"/>
<Setter Property="Template" Value="{StaticResource WindowTemplate}"/>
</Style>
我的文件资源文件后面还有代码来实现常用功能(如关闭,拖动窗口等)。
public partial class WindowToolStyle : ResourceDictionary
{
public WindowToolStyle()
{
InitializeComponent();
}
private void titleBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var window = (Window)((FrameworkElement)sender).TemplatedParent;
window.DragMove();
}
}
然后我使用Style =&#34; {StaticResource WindowToolStyle}&#34;
设置我的窗户样式问题是我需要从使用此模板设置样式的窗口访问控件模板中声明的对象,我该怎么做?谢谢!
(我按照这篇文章来做上面的http://www.codeproject.com/Articles/71485/Reusing-Control-Templates-in-Resource-Dictionaries,我的动机是创建一个可以被我们所有工具使用的窗口模板,这样我们就不会重复代码了)
答案 0 :(得分:-1)
http://paulstovell.com/blog/wpf-part-names
在窗口中使用templatePart属性然后在OnApplyTemplate()中获取参考模板中的部件