下面的 UserControl 效果很好,但我想让更改样式更容易。
我尝试过的一件事是将样式移动到 ResourceDictionary 中的通用按钮样式中,但这会出现错误,如下所示。
我尝试的另一件事是将其转换为自定义控件,但这是这个问题的主题
目前有几个类似的按钮被定义为 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
用户控件 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>
用户控制代码背后
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());
}
}