Create custom binding property for window.resources style

前端 未结 1 885
眼角桃花
眼角桃花 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

    make sure that template know how to use that property

    
        
    
    

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

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