What are the defaults for Binding.Mode=Default for WPF controls?

后端 未结 3 1215
情话喂你
情话喂你 2020-12-28 11:37

In WPF Binding.Mode, when selecting Default, it depends in the property being binded.

I am looking for some list or some convention or any information for the defaul

3条回答
  •  礼貌的吻别
    2020-12-28 12:10

    Was looking for a list as well, mostly to find out which bindings could be set to one-way to improve performance. The following functions can help you find which controls use two-way binding by default:

    public IList GetAttachedProperties(DependencyObject obj)
    {
        var result = new List();
        foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(obj, new Attribute[] { new PropertyFilterAttribute(PropertyFilterOptions.Valid) }))
        {
            var dpd = DependencyPropertyDescriptor.FromProperty(pd);
            if (dpd != null)
            {
                result.Add(dpd.DependencyProperty);
            }
        }
        return result;
    }
    
    public bool IsBindsTwoWayByDefault(DependencyObject obj, DependencyProperty property)
    {
        var metadata = property.GetMetadata(obj) as FrameworkPropertyMetadata;
        if (metadata != null)
        {
            return metadata.BindsTwoWayByDefault;
        }
        return false;
    }
    

    Using a print function, gives us a list:

    var objList = new List { new TextBox(), new TextBlock(), new Label(), new ComboBox(), new Button() };
    foreach (var obj in objList)
    {
        var props = GetAttachedProperties(obj);
        foreach (var prop in props)
        {
            if(IsBindsTwoWayByDefault(obj, prop))
                Debug.WriteLine($"{obj} : {prop.OwnerType}:{prop.Name}");
        }
    }
    

    Sample result (control properties with two-way binding as default)

    System.Windows.Controls.TextBox : System.Windows.Controls.TextBox:Text
    System.Windows.Controls.TextBox : System.Windows.Controls.TextSearch:Text
    System.Windows.Controls.TextBlock : System.Windows.Controls.TextSearch:Text
    System.Windows.Controls.Label : System.Windows.Controls.TextSearch:Text
    System.Windows.Controls.ComboBox Items.Count:0 : System.Windows.Controls.ComboBox:IsDropDownOpen
    System.Windows.Controls.ComboBox Items.Count:0 : System.Windows.Controls.ComboBox:Text
    System.Windows.Controls.ComboBox Items.Count:0 : System.Windows.Controls.Primitives.Selector:SelectedIndex
    System.Windows.Controls.ComboBox Items.Count:0 : System.Windows.Controls.Primitives.Selector:SelectedItem
    System.Windows.Controls.ComboBox Items.Count:0 : System.Windows.Controls.Primitives.Selector:SelectedValue
    System.Windows.Controls.ComboBox Items.Count:0 : System.Windows.Controls.TextSearch:Text
    System.Windows.Controls.Button : System.Windows.Controls.TextSearch:Text
    

    Interestingly, most controls have a TextSearch property which has two-way binding.

提交回复
热议问题