XAML如何在派生的UserControl类中拥有StaticResource

时间:2013-04-14 12:55:24

标签: c# wpf visual-studio-2010 xaml styles

我有以下问题。我有一个派生自UserControl的类,这里是代码:

public partial class MyUC : UserControl
{
[...]
    public bool IsFlying { get { return true; } }
[...]
}    

我想使用为MyUC类创建的样式,下面是样式代码。它位于App.Xaml:

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dc="clr-namespace:MyNamespace"
<Application.Resources>
    <Style x:Key="mystyle" TargetType="dc:MyUC ">
        <Style.Triggers>
            <Trigger Property="IsFlying" Value="true">
                <Setter Property = "Background" Value="Blue"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</Application.Resources>

如您所见,我想使用我在MyUC中声明的属性。 问题是当我尝试向我的控件添加样式时,会出现错误。

<UserControl x:Class="MyNamespace.MyUC"
         [...]
         Style="{StaticResource mystyle}"> 
<UserControl.Resources>
</UserControl.Resources>
</UserControl>

错误是:&#39; MyUC&#39; TargetType与元素类型&#39; UserControl&#39;

不匹配

据我所知,编译器不识别从UserControl派生的类MyUC。如何解决?

提前致谢!

1 个答案:

答案 0 :(得分:2)

错误可能仅在design时间,它应该在runtime处理正常。运行您的应用程序,看看它是否适合您。

此外,您的触发器不适用于normal CLR property,您需要将其设为Dependency Property -

    public bool IsFlying
    {
        get { return (bool)GetValue(IsFlyingProperty); }
        set { SetValue(IsFlyingProperty, value); }
    }

    public static readonly DependencyProperty IsFlyingProperty =
        DependencyProperty.Register("IsFlying", typeof(bool), 
           typeof(SampleUserControl), new UIPropertyMetadata(true));

此外,您可以从样式声明中删除x:Key="mystyle"。它将自动应用于您的UserControl。

这样您就不必在UserControl上显式设置样式。这一行不需要 - Style="{StaticResource mystyle}"

相关问题