我是Silverlight的新手,我想完成一项相对简单的任务:
创建一个“面板”控件,显示标题和一些子内容。
我能够在一定程度上获得这项工作,但XAML的位置确实让我感到困惑。
在我的页面上,我使用我的控件。这导致我的面板在子内容区域显示为蓝色,顶部有20px黄色标题,上面写着“下面是一些内容”。
<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和资源的概念我错了?
答案 0 :(得分:3)
David,您需要为您的样式创建一个键,并通过它的Style属性在面板中引用它...它是Silverlight的一个限制,它不允许您创建适用于所有的“全局”样式某种类型的元素。
当您将注意事项放置在主题中时,此行为会有所不同。
另一种方法是将样式放在面板本身的ResourceDictionary而不是页面/用户控件中,但是你不能在其他面板中重用该样式。