我试图制作一个从按钮派生的CustomControl,该按钮仅显示为彩色的矩形。我想在控件上设置两个属性,我可以设置它们,它们指定普通颜色(ColdColor),以及鼠标悬停在控件上时使用的另一种颜色(HotColor)。将控件模板中的属性绑定到画笔的颜色
我想不出如何获得刷子颜色和控件属性之间的绑定设置。这是我的代码:
Generic.xaml:
<Style TargetType="{x:Type local:TestCustomControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:TestCustomControl}">
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Name="MyBorder">
<Border.Background>
<!-- This works: -->
<!--<SolidColorBrush Color="Green" />-->
<!-- This doesn't work: -->
<SolidColorBrush Color="{TemplateBinding ColdColor}" />
</Border.Background>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver">
<Storyboard>
<!-- This works: -->
<!--<ColorAnimation Storyboard.TargetProperty="Background.Color" Storyboard.TargetName="MyBorder" To="Red" Duration="0:0:0.2"/>-->
<!-- This doesn't work: -->
<ColorAnimation Storyboard.TargetProperty="Background.Color" Storyboard.TargetName="MyBorder" To="{TemplateBinding HotColor}" Duration="0:0:0.2"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
TestCustomControl.cs:
public class TestCustomControl : Button
{
static TestCustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TestCustomControl), new FrameworkPropertyMetadata(typeof(TestCustomControl)));
}
public Color HotColor
{
get { return (Color)GetValue(HotColorProperty); }
set { SetValue(HotColorProperty, value); }
}
// Using a DependencyProperty as the backing store for HotColor. This enables animation, styling, binding, etc...
public static readonly DependencyProperty HotColorProperty =
DependencyProperty.Register("HotColor", typeof(Color), typeof(TestCustomControl), new UIPropertyMetadata(new Color()));
public Color ColdColor
{
get { return (Color)GetValue(ColdColorProperty); }
set { SetValue(ColdColorProperty, value); }
}
// Using a DependencyProperty as the backing store for ColdColor. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ColdColorProperty =
DependencyProperty.Register("ColdColor", typeof(Color), typeof(TestCustomControl), new UIPropertyMetadata(new Color()));
}
用法在MainWindow.xaml:
<my:TestCustomControl ColdColor="#FF0000AF" HotColor="#FFFF00AF"/>
编辑:如果说“不起作用“意味着TestCustomControl完全透明。
谢谢,但它仍然不起作用,即TestCustomControl完全透明。 – NPVN 2010-12-01 11:06:02