C# XAML如何在派生的UserControl类中拥有StaticResource
我有以下问题。我有一个从UserControl派生的类,下面是代码:C# XAML如何在派生的UserControl类中拥有StaticResource,c#,wpf,visual-studio-2010,xaml,styles,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"
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>
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dc=“clr命名空间:MyNamespace”
如您所见,我想使用我在MyUC中声明的属性。
问题是,当我尝试向控件添加样式时,会发生错误
<UserControl x:Class="MyNamespace.MyUC"
[...]
Style="{StaticResource mystyle}">
<UserControl.Resources>
</UserControl.Resources>
</UserControl>
错误是:“MyUC”TargetType与元素“UserControl”的类型不匹配。
据我所知,编译器不识别从UserControl派生的类MyUC。如何修复它
提前谢谢 错误可能仅在
设计时出现,它在运行时应能正常工作。运行你的应用程序,看看它是否适合你
此外,触发器对普通CLR属性
不起作用,您需要将其设置为依赖属性
-
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上设置样式。那么就不需要这一行了-Style=“{StaticResource mystyle}”
谢谢你的回复。它恰到好处。注册依赖属性修复了我的代码。