【发布时间】:2009-06-05 00:33:52
【问题描述】:
我是 Silverlight 的新手,我想完成一个相对简单的任务:
创建一个显示标题和一些子内容的“面板”控件。
我能够在一定程度上完成这项工作,但 XAML 的放置确实让我感到困惑。
在我的页面上,我使用我的控件。这导致我的面板在子内容区域中显示一个蓝色按钮,顶部有一个 20 像素的黄色标题,上面写着“下面是一些内容”。
<UserControl x:Class="SilverlightApplication9.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SilverlightApplication9">
<Grid Background="White">
<local:MyPanel Background="Blue">
<Button Width="50" Height="25" Content="Hello"></Button>
</local:MyPanel>
</Grid>
</UserControl>
我的面板源码很简单,只是:
public partial class MyPanel : ContentControl
{
public MyPanel()
{
DefaultStyleKey = typeof(MyPanel);
InitializeComponent();
}
}
这是一个部分类,并且有一个附加的 XAML 文件,这是我开始困惑的地方:
如果我尝试将我的样式/模板代码放入部分类 XAML 文件中,它似乎被忽略了(显示了我的按钮,但缺少颜色和文本等其他内容)
<ContentControl x:Class="SilverlightApplication9.MyPanel"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SilverlightApplication9">
<ContentControl.Resources>
<ResourceDictionary>
<Style TargetType="local:MyPanel">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyPanel">
<Grid Background="Yellow">
<Grid.RowDefinitions>
<RowDefinition Height="20" />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock HorizontalAlignment="Center" Height="20" Grid.Row="0" Text="Below is some content"/>
<Grid Grid.Row="1" Background="LightBlue">
<ContentPresenter />
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
</ContentControl.Resources>
</ContentControl>
但是,如果我创建一个 \Themes\generic.xaml 文件并粘贴相同的代码,它就可以工作
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SilverlightApplication9"
xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows"
>
<Style TargetType="local:MyPanel">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyPanel">
<Grid Background="Yellow">
<Grid.RowDefinitions>
<RowDefinition Height="20" />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock HorizontalAlignment="Center" Height="20" Grid.Row="0" Text="Below is some content"/>
<Grid Grid.Row="1" Background="LightBlue">
<ContentPresenter />
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
我显然遗漏了有关如何在项目中处理或使用资源或 XAML 文件的重要信息(在 Silverlight 之前我没有任何 WPF 经验)。
我做错了什么导致我无法将面板的模板代码放入面板的 xaml 文件中?是否有一些关于 XAML 和资源的概念我弄错了?
【问题讨论】:
标签: silverlight xaml resources