And*_*rew 4 wpf templates wpf-controls
我似乎在创建派生自System.Windows.Window的自定义窗口类型时遇到了一些麻烦.似乎有两个问题正在发生.首先,有一个编译时错误说明
在'Control'类型上找不到静态成员'ContentProperty'
这是对自定义窗口的ControlTemplate中的ContentPresenter元素的引用(请参阅下面的BaseWindowResource.xaml的代码示例).我不知道为什么会这样,因为BaseWindow派生自Window,因此必须有一个Content属性......
第二个问题是,当从BaseWindow派生的Window1完成渲染时,我似乎无法触发BaseWindow的ContentRendered事件...我需要处理BaseWindow中的ContentRendered事件,因为处理程序将包含很多代码,否则需要复制到每个派生类...
无论如何,这是代码.任何帮助都感激不尽!
干杯,
安德鲁
App.xaml中:
<Application x:Class="WpfApplication4.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Window1.xaml">
<Application.Resources>
<ResourceDictionary Source="/BaseWindowResource.xaml" />
</Application.Resources>
</Application>
Run Code Online (Sandbox Code Playgroud)
BaseWindowResource.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication4">
<Style TargetType="{x:Type local:BaseWindow}" x:Key="BaseWindowStyleKey">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid>
<Rectangle Margin="20" Fill="Green" x:Name="MyRect" />
<ContentPresenter Margin="30" x:Name="MyContentPresenter"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)
BaseWindow.cs:
public class BaseWindow : Window
{
public BaseWindow()
{
Style = FindResource("BaseWindowStyleKey") as Style;
ContentRendered += new EventHandler(BaseWindow_ContentRendered);
}
void BaseWindow_ContentRendered(object sender, EventArgs e)
{
ContentPresenter contentPresenter = Template.FindName("MyContentPresenter", this) as ContentPresenter;
MessageBox.Show(String.Format("The dimensions for the content presenter are {0} by {1}",
contentPresenter.ActualWidth,
contentPresenter.ActualHeight));
}
}
Run Code Online (Sandbox Code Playgroud)
Window1.xaml:
<local:BaseWindow x:Class="WpfApplication4.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication4"
Title="Window1" Height="300" Width="300">
</local:BaseWindow>
Run Code Online (Sandbox Code Playgroud)
最后是Window1.xaml.cs:
public partial class Window1 : BaseWindow
{
public Window1()
{
InitializeComponent();
}
}
Run Code Online (Sandbox Code Playgroud)
嗯,这就是所有的代码.它几乎隔离了问题.
干杯,
安德鲁
尝试指定类似如下的类型:
Content="{TemplateBinding Window.Content}"
Run Code Online (Sandbox Code Playgroud)
我认为第二个问题与第一个问题有关.如果此解决方案未解决第二个问题,请在此处发表评论.