カスタム プロパティで指定された色で始まり、ハードコードされた色で終わる、背景のグラデーションを表示する Button コントロールを作成しようとしています。これは簡単なコントロール テンプレートのように思えますが、機能させることができません。
Color
依存関係プロパティを持つサブクラス化された「ボタン」 :
public class GradientButton : Button
{
public Color BackgroundColor
{
get { return (Color)GetValue(BackgroundColorProperty); }
set { SetValue(BackgroundColorProperty, value); }
}
public static readonly DependencyProperty BackgroundColorProperty =
DependencyProperty.Register("BackgroundColor", typeof(Color), typeof(GradientButton), new PropertyMetadata((sender, args) => {
System.Diagnostics.Debug.WriteLine("Set bg col");
}));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(GradientButton), null);
public GradientButton()
: base()
{
this.DefaultStyleKey = typeof(GradientButton);
}
}
BackgroundColor
DPを使用して背景のグラデーションを設定するコントロール テンプレート:
<Style TargetType="custom:GradientButton">
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="VerticalAlignment" Value="Top" />
<Setter Property="Width" Value="200" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="custom:GradientButton">
<Grid>
<Grid.Background>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Color="{TemplateBinding BackgroundColor}" Offset="0" />
<GradientStop Color="Gray" Offset="1" />
</LinearGradientBrush>
</Grid.Background>
<TextBlock Text="{TemplateBinding Text}" />
<TextBlock Text="{TemplateBinding BackgroundColor}" HorizontalAlignment="Right" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
次のようなコントロールを使用する場合:
<custom:GradientButton Text="Foo" BackgroundColor="#FF0000" />
次に、赤から灰色へのグラデーションの背景を持つボタンが表示されることを期待しています。代わりに、グラデーションの灰色の部分のみが表示されます。
私が見逃している痛々しいほど明らかなことは何ですか?
強調のために編集:
- DP / TemplateBindingが実際にコーシャであることを証明するために、「テキスト」DPを追加しました。
- テキストブロック内のテキストとしても、「BackgroundColor」を表示できないことに注意してください。ただし、実際にはコントロールに設定されていることをデバッガーで確認しました。