Create custom binding property for window.resources style

前端 未结 1 884
眼角桃花
眼角桃花 2020-12-22 13:30

I\'ve created a couple of custom bindings for a custom control before, but since this case is for a window.resources style for a button, (A control template rather), I don\'

相关标签:
1条回答
  • 2020-12-22 14:26

    Creating a viewmodel to customize wpf button colors is a wrong approach. Button color scheme is something which belongs strictly to a view. Also many buttons means many view model instances, since each button might want to be unique - too much code for such a simple setting.

    Button class doesn't have enough dependency properties to set color representing HoverColorBackground/HoverColorBorder/HoverColorForeground. Alternatives are to create a derived Button class (way to go when DP are of some complex type and/or have associated logic) or use attached properties. I have written a tip, which coveres the second approach.

    short version

    create an attached DP

    public static class Alt
    {
        #region Background
        public static readonly DependencyProperty BackgroundProperty =
                  DependencyProperty.RegisterAttached("Background", typeof(Brush),
                  typeof(Alt), new PropertyMetadata(null));
    
        public static Brush GetBackground(DependencyObject obj)
        {
            return (Brush)obj.GetValue(Alt.BackgroundProperty);
        }
    
        public static void SetBackground(DependencyObject obj, Brush value)
        {
            obj.SetValue(Alt.BackgroundProperty, value);
        }
        #endregion
    }
    

    set custom value for that property

    <Button Content="Blue" Foreground="White" Margin="5"
            Background="Blue" ui:Alt.Background="DarkBlue"/>
    

    make sure that template know how to use that property

    <Trigger Property="IsMouseOver" Value="True">
        <Setter TargetName="ButtonGrid" 
                Property="Background" 
                Value="{Binding Path=(ui:Alt.Background),
                                RelativeSource={RelativeSource TemplatedParent}}"/>
    </Trigger>
    

    Works for any control. Many DP can be mixed in any combination.

    0 讨论(0)
提交回复
热议问题