我试图更改自定义控件矩形的背景颜色。如果我的属性(bool)为setSelected==true
,则颜色应为Red
。如果为setSelected==false
,则颜色应为Transparent
。
如何更改Rectangle
的装订背景颜色?
通用:
<Style TargetType="{x:Type local:IdnStatusRect}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:IdnStatusRect}">
<Border Background="Transparent"
BorderBrush="Purple"
BorderThickness="0">
<DockPanel HorizontalAlignment="Center" VerticalAlignment="Center" Width="15" Height="15" Background="Transparent">
<Grid>
<Rectangle Width="15" Height="15" Fill="Transparent" Stroke="#97CDEB" StrokeThickness="1"/>
<Grid.Background>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Color="{Binding Path=BackgroundColor, RelativeSource={RelativeSource TemplatedParent}}" Offset="0" />
</LinearGradientBrush>
</Grid.Background>
</Grid>
</DockPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
状态矩形:
public class IdnStatusRect : Control
{
public bool setSelected
{
get { return (bool)GetValue(setSelectedPropert); }
// set { SetValue(RectPropert1, Application.Current.FindResource(value.ToString())); }
set { SetValue(setSelectedPropert, value); }
}
public static readonly DependencyProperty setSelectedPropert =
DependencyProperty.Register("setSelected", typeof(bool), typeof(IdxButton), new UIPropertyMetadata(false));
public Color BackgroundColor
{
get { return (Color)GetValue(setSelectedPropert); }
set { SetValue(BackgroundColorProperty, FindResource("TextColor1")); }
}
public static readonly DependencyProperty BackgroundColorProperty =
DependencyProperty.Register("BackgroundColor", typeof(Color), typeof(IdxButton), new PropertyMetadata((sender, args) => {
System.Diagnostics.Debug.WriteLine("Set bg col");
}));
static IdnStatusRect()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(IdnStatusRect), new FrameworkPropertyMetadata(typeof(IdnStatusRect)));
}
1条答案
按热度按时间xkftehaa1#
您可以将触发器添加到监视
SetSelected
属性的控件模板中。您需要将x:Name
分配给Rectangle
,以便在setter中使用TargetName
引用它。另一个选项是使用具有相对源绑定的
Rectangle
的样式。请考虑将依赖项属性与约定保持一致。
Property
结尾。IdxButton
与控件类型IdnStatusRect
不对应。***提示:**使用
nameof
而不是硬编码字符串引用 Package 属性名称.