以下の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());
}
}