我遇到以下问题。我有一个派生自 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。如何解决?
提前致谢!
最佳答案
错误可能仅出现在设计
时,它在运行时
应该可以正常工作。运行您的应用程序,看看它是否适合您。
此外,您的触发器不适用于普通 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}"
关于c# - XAML 如何在派生的 UserControl 类中拥有 StaticResource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15999277/