0

以下のUserControlはうまく機能しますが、スタイルを簡単に変更できるようにしたいと思います。

私が試したことの1つは、スタイルをResourceDictionaryの一般的なボタンスタイルに移動することですが、以下に示すようなエラーが発生します。

私が試したもう1つのことは、これをカスタムコントロールに変換することですが、それがこの質問の主題です。

現在UserControlsとして定義されている同様のボタンがいくつかあります。それらすべてのスタイルを変更するための推奨される方法はありますか?

乾杯

別のスタイルを使用してスタイルを適用しようとして失敗しました

<Style TargetType="{x:Type Button}">
    <Setter Property="Style" Value="{StaticResource blueButtonStyle}"/>
</Style>

Error: Style object is not allowed to affect the style property of the object to which it applies

UserControl XAML

<UserControl.Resources>
    <ResourceDictionary Source="pack://application:,,,/Smack.Core.Presentation.Wpf;component/Themes/generic.xaml" />
</UserControl.Resources>

<Button x:Name="_button" Style="{StaticResource blueButtonStyle}" Command="{Binding AddNewItemCommand}"  >
    <StackPanel Orientation="Horizontal" >
        <Image Source="{resx:Resx ResxName=Smack.Core.Presentation.Resources.MasterDetail, Key=bullet_add}" Stretch="Uniform" VerticalAlignment="Center" />
        <AccessText x:Name="_accesText" VerticalAlignment="Center">_Add New Subject</AccessText>
        <ContentPresenter/>
    </StackPanel>
</Button>

背後にあるUserControlコード

public partial class AddNewItemButton : UserControl
{
    public AddNewItemButton() { InitializeComponent(); }

    public static readonly DependencyProperty SubjectProperty = DependencyProperty.Register(
        "Subject", typeof (string), typeof (AddNewItemButton),
        new FrameworkPropertyMetadata(OnSubjectChanged));

    public string Subject { get { return (string) GetValue(SubjectProperty); } set { SetValue(SubjectProperty, value); } }

    private static void OnSubjectChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) {
        var control = obj as AddNewItemButton;
        if (control == null) return;

        control._accesText.Text = "_" + string.Format(MasterDetail.Subject_AddNew_Label, control.Subject.Capitalize());

        control._button.ToolTip = string.Format(MasterDetail.Subject_AddNew_ToolTip, control.Subject.ToLower());
    }

}
4

1 に答える 1

7

最初のアプローチを使用すると、運が良くなる可能性があります。

<Style TargetType="{x:Type Button}">
    <Setter Property="Style" Value="{StaticResource blueButtonStyle}"/>
</Style>

スタイル内からスタイルを設定するとエラーが発生することは理解できます。代わりに、「BasedOn」属性を使用して、「デフォルト」スタイルを強制的に目的のスタイルから継承することができます。

<Style TargetType="{x:Type Button}" BasedOn="{StaticResource blueButtonStyle}">
    <!-- Nothing Here --> 
</Style>

それはあなたが望むことをするはずです。つまり、私があなたの質問を正しく理解している場合(正直に言うと、少し不明確に思えます)。

ちなみに、このボタンにカスタムユーザーコントロールを使用する理由は実際にはありません。これはすべて通常のボタンで実行でき、BindingsやConvertersなどのWPFのコアツールを使用して、ボタンのコンテンツとツールチップに動的に変化するテキストを表示します。

于 2012-04-27T13:38:07.270 に答える