我試圖製作一個從按鈕派生的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