无法更改自己的属性样式
我在自定义控件类 DataPoint 中创建依赖属性:
public abstract class DataPoint : Control
{
public Color BaseColor
{
get { return (Color)GetValue(BaseColorProperty); }
set { SetValue(BaseColorProperty, value); }
}
public static readonly DependencyProperty BaseColorProperty =
DependencyProperty.Register("BaseColor", typeof(Color), typeof(DataPoint), new UIPropertyMetadata(Colors.DarkRed));
// Other class stuff
}
然后创建其他自定义控件 AreaDataPoint 继承 DataPoint:
public class AreaDataPoint : DataPoint
{
static AreaDataPoint()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(AreaDataPoint), new FrameworkPropertyMetadata(typeof(AreaDataPoint)));
}
// Other class stuff
}
在 xaml 中,我尝试将值分配给 BaseColor 属性,但它不起作用
<Style TargetType="{x:Type local1:AreaDataPoint}">
<Setter Property="BaseColor" Value="DarkGreen" />
</Style>
I'm creating dependency property in my custom controll class DataPoint:
public abstract class DataPoint : Control
{
public Color BaseColor
{
get { return (Color)GetValue(BaseColorProperty); }
set { SetValue(BaseColorProperty, value); }
}
public static readonly DependencyProperty BaseColorProperty =
DependencyProperty.Register("BaseColor", typeof(Color), typeof(DataPoint), new UIPropertyMetadata(Colors.DarkRed));
// Other class stuff
}
Then I create other custom control AreaDataPoint inheriting DataPoint:
public class AreaDataPoint : DataPoint
{
static AreaDataPoint()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(AreaDataPoint), new FrameworkPropertyMetadata(typeof(AreaDataPoint)));
}
// Other class stuff
}
In xaml I'm trying to assign value to BaseColor property, but it doesn't work
<Style TargetType="{x:Type local1:AreaDataPoint}">
<Setter Property="BaseColor" Value="DarkGreen" />
</Style>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在设置“Background”属性,而不是“BaseColor”属性?
请记住,您可能需要一个转换器来获取字符串
DarkGreen
并将其转换为Color
实例。You're setting the "Background" property, not the "BaseColor" property?
Bear in mind you might need a converter to take the string
DarkGreen
and convert it to aColor
instsance.您如何确定它“不起作用”。从您的代码中的内容来看,一切都是正确的,因此您可能在其他地方做了一些导致 Style 值丢失的事情。您是否可以在代码或 XAML 中的某处设置 BaseColor 的本地值?您是否已验证使用 BaseColor 属性的位置实际上正确地提取了值?直接使用颜色也不常见 - 大多数情况(前景、背景、形状填充)都使用画笔,所以我也会检查一下。
How are you determining that it "doesn't work". From what's in your code here everything is correct so you may be doing something elsewhere that's causing the Style value to get lost. Are you possibly setting a local value for the BaseColor somewhere in code or XAML? Have you verified that where you're using the BaseColor property is actually pulling the value correctly? It's also not common to use a Color directly - most situations (Foregrounds, Backgrounds, Shape Fills) use Brushes so I'd check that too.