【问题标题】:XAML How to own StaticResource in derived UserControl classXAML 如何在派生的 UserControl 类中拥有 StaticResource
【发布时间】:2013-04-14 12:55:23
【问题描述】:

我有以下问题。我有一个派生自 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>

错误是:'MyUC' TargetType 与元素'UserControl'的类型不匹配。

据我了解,编译器无法识别从 UserControl 派生的 MyUC 类。如何解决?

提前致谢!

【问题讨论】:

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


    【解决方案1】:

    错误可能只出现在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}"

    【讨论】:

    • 非常感谢您的好评。它击中了现场。注册依赖属性修复了我的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 2010-12-27
    • 1970-01-01
    • 1970-01-01
    • 2011-03-30
    • 2011-03-11
    • 1970-01-01
    相关资源
    最近更新 更多