DataTrigger Binding in WPF Style

前端 未结 1 774
太阳男子
太阳男子 2020-12-18 22:41

I have the following Button and Style in WPF and I need to generalize the Binding in the DataTrigger section because I have near 10 similar buttons in the same Window and ea

1条回答
  •  半阙折子戏
    2020-12-18 22:55

    could you provide me an example of what you explained?

    Sure,

    1 - Using Tag

    In your Style have your DataTrigger as:

    
      ...
    
    

    as for usage:

    2 - Using Attached Property:

    "local:" refers to the xaml namespace alias of your application or if you use different namespaces, the namespace where MyCustomPropertyCollection is declared.

    code-behind:

    public class MyCustomPropertyCollection {
      public static readonly DependencyProperty SomeStringProperty =
        DependencyProperty.RegisterAttached(
          "SomeString",
          typeof(string),
          typeof(MyCustomPropertyCollection),
          new FrameworkPropertyMetadata(string.Empty));
    
      public static void SetSomeString(UIElement element, string value) {
        element.SetValue(SomeStringProperty, value);
      }
    
      public static string GetSomeString(UIElement element) {
        return (string)element.GetValue(SomeStringProperty);
      }
    }
    

    Style.DataTrigger

    
      ...
    
    

    usage:

    3 - Normal Dependency Property

    custom Button class:

    public class MyButton : Button {
      public static readonly DependencyProperty SomeStringProperty =
        DependencyProperty.Register(
          "SomeString",
          typeof(string),
          typeof(MyButton),
          new FrameworkPropertyMetadata(string.Empty));
    
      public string SomeString {
        get {
          return (string)GetValue(SomeStringProperty);
        }
        set {
          SetValue(SomeStringProperty, value);
        }
      }
    }
    

    Style in xaml not only needs DataTrigger updated but Style definition too.

    so switch