当前位置:网站首页>Dependent properties, dependent additional properties, and type conversions

Dependent properties, dependent additional properties, and type conversions

2022-06-25 10:21:00 @@Mr.Fu

One 、 Dependency property

1、 The meaning and function of dependency properties

   Data binding 

2、 Define dependency properties

         basic : Statement    register    packing 
        //1   Statement 
        public static DependencyProperty valueProperty;
       //2    register  
        static DependenProperties()
        {
            valueProperty = DependencyProperty.Register("value", typeof(string), typeof(DependenProperties),new PropertyMetadata(default(string)));
        }
        //3  packing  
        public string value
        {
            get
            {
                return (string)this.GetValue(valueProperty);
            }
            set
            {
               this.SetValue(valueProperty, " Xiao Ming ");
            }
        }
 remarks : Must inherit in class  DependencyObject

3、 Dependent property callback methods and parameters

 ValidateValueCallback : Property value validation callback 
  //2    register  
 static DependenProperties()
 {
    valueProperty = DependencyProperty.Register("value", typeof(string), typeof(DependenProperties),new PropertyMetadata(default(string),new PropertyChangedCallback (OnValueChangedCallback)),new ValidateValueCallback(OnValidateValueCallback));
 }
// Callback method must be static 
// Parameter one :DependencyObject  :  The object of the property   
// Parameter two :DependencyPropertyChangedEventArgs :  The data associated with the change action 
public static void  OnValueChangedCallback(DependencyObject  o,DependencyPropertyChangedEventArgs arg)
{
    ...... 
}
// Verify callback function 
// Parameter one :Object : Property to write to 【 Latest value 】
// Return value :bool  type : Write allowed 
public static bool  OnValidateValueCallback(Object o)
{
    ...... 
   return true;
}
 CoerceValueCallback: Forced value callback 

   The code is as follows :
  //2    register  
 static DependenProperties()
 {
    valueProperty = DependencyProperty.Register("value", typeof(string), typeof(DependenProperties),new PropertyMetadata(default(string),new PropertyChangedCallback (OnValueChangedCallback),new CoerceValueCallback() ),new ValidateValueCallback(OnValidateValueCallback));
 }
// Callback method must be static 
// Parameter one :DependencyObject  :  The object of the property   
// Parameter two :DependencyPropertyChangedEventArgs :  The data associated with the change action 
public static void  OnValueChangedCallback(DependencyObject  o,DependencyPropertyChangedEventArgs arg)
{
    ...... 
}
// Verify callback function 
// Parameter one :Object : Property to write to 【 Latest value 】
// Return value :bool  type : Write allowed 
public static bool  OnValidateValueCallback(Object o)
{
    ...... 
   return true;
}
// Force callback function 
// <param name="d"> Property object </param>
/// <param name="baseValue"> The latest value of the current property </param>
/// <returns> The value you want the property to receive </returns>
public  static void OnCoerceValueCallback(DependencyObject d, object baseValue)
{
     return  null;
}
 PropertyChangedCallback: Property change callback 

   The code is as follows :
  //2    register  
 static DependenProperties()
 {
    valueProperty = DependencyProperty.Register("value", typeof(string), typeof(DependenProperties),new PropertyMetadata(default(string),new PropertyChangedCallback (OnValueChangedCallback) ));
 }
// Callback method must be static 
// Parameter one :DependencyObject  :  The object of the property   
// Parameter two :DependencyPropertyChangedEventArgs :  The data associated with the change action 
public static void  OnValueChangedCallback(DependencyObject  o,DependencyPropertyChangedEventArgs arg)
{
    ...... 
}

Be careful :

​ Property registration : 【 recommend 】

// Property registration 
 static CallBack() 
        {
            ValueProperty = DependencyProperty.Register(
                "Value",
                typeof(string),
                typeof(CallBack),
                new FrameworkPropertyMetadata(default(string),  FrameworkPropertyMetadataOptions.BindsTwoWayByDefault|  FrameworkPropertyMetadataOptions.AffectsMeasure,
                new PropertyChangedCallback(OnValueChangesCallBack),new CoerceValueCallback (OnCoerceValueCallback)),
                new ValidateValueCallback(ValidateValueCallback)
                );
        }
//FrameworkPropertyMetadata  Object ratio PropertyMetadata A few more parameters :
// Among them  FrameworkPropertyMetadataOptions. |  FrameworkPropertyMetadataOptions.  Option parameters , The value of the page will change when it is re rendered , Redisplay the latest value . 
//FrameworkPropertyMetadataOptions Options :

//AffectsArrange、AffectsMeasure、AffectsParentArrange、AffectsParentMeasure: When attributes change , The container needs to be notified for re measurement and rearrangement .Margin When the value changes , It will crowd out adjacent objects 

//AffectsRender: The change of attribute value causes the element to be re rendered 、 Redraw 

//BindsTwoWayByDefault: By default, the binding behavior is handled in a two-way binding manner 

//Inherits: Inherit .FontSize, When the parent object sets this property , Will have the same effect on sub objects 

//IsAnimationProhibited: This property cannot be used for animation 

//IsNotDataBindable: You can't use expressions , Set dependent properties 

//Journal:Page Development , The value of the property will be saved to   journal 

//SubPropertiesDoNotAffectRender: When the sub attributes of object properties change , Don't re render objects 

//DefaultValue: The default value is 

Enter attribute value -----> Trigger validation callback ------>【 Verification passed 】-----> Write to attribute value ------>【 After the value changes 】------> Trigger property change callback -----> Force callback .

4、 Rely on additional properties

1、 The meaning and function of dependent additional attributes
Provide dependent properties to other objects .
For example, some attributes cannot be bound .【password】
2、 Define dependency properties 【 newly build Controller class :】
basic :
Statement
  public static DependencyProperty PasswordValueProperty;
register
   public static readonly DependencyProperty MyPropertyProperty =
            DependencyProperty.RegisterAttached("PasswordValue", typeof(string), typeof(Controller), 
                new PropertyMetadata(default(string), 
                    new PropertyChangedCallback(OnPropertyChangedCallback) )
                
                );
packing
      public static string  GetPasswordValue(DependencyObject obj)
        {
            return (string)obj.GetValue(MyPropertyProperty);
        }

        public static void SetPasswordValue(DependencyObject obj, string  value)
        {
            obj.SetValue(MyPropertyProperty, value);
        }

Callback function triggered after the value changes

  public static void OnPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            (d as PasswordBox).Password = (string)e.NewValue;   
        }
xmal The code is as follows :
<Window x:Class="WpfApp1.DependenProperties.DependenProperties"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1.DependenProperties"
        xmlns:sys="clr-namespace:System;assembly=System.Runtime"
        mc:Ignorable="d"
        Title="DependenProperties" Height="450" Width="800">
    <Window.Resources>
        <sys:String x:Key="pwd">123</sys:String>
    </Window.Resources>
    <Grid>
        <PasswordBox Password="" local:Controller.PasswordValue="{Binding Source={StaticResource pwd}}"></PasswordBox> 
    </Grid>
</Window>

3、 Main callback

​ Callbacks are used just like dependent properties .

4、 Attribute metadata parameter

​ As with dependent properties .

5、 Use scenarios
6、 Summary of differences from dependent attributes
Dependency property : Must be in the dependent object , Additional attributes are not necessarily .
5、 Type converter

​ Create a new dependent attribute class : 【Control】

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace WpfApp1.TypeConverterDemo
{
    [TypeConverter(typeof(TypeConvertDemo))]
    public class Control
    {
        public double Width { get; set; }   
        public double Height { get; set; }

    }

    public class ControlProperty:ContentControl { 
        public Control Value
        {
            get { return (Control)GetValue(ValueProperty); }
            set { SetValue(ValueProperty, value); }
        }
 
        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register("Value", typeof(Control), typeof(ControlProperty), new PropertyMetadata(null)); 

    }
}

​ Create a new data type conversion class :【TypeConvertDemo】 Inherit TypeConverter

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApp1.TypeConverterDemo
{
    public class TypeConvertDemo : TypeConverter
    {
        /// <summary>
        /// Type conversion 
        /// </summary>
        /// <param name="context"> Context </param>
        /// <param name="culture"> Current localization information </param>
        /// <param name="value"> Transfer value </param>
        /// <returns></returns>
        public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value)
        {
            var temp = Convert.ToString(value).Split(',');
            var c = new Control()
            {
                Width = Convert.ToDouble(temp[0]),
                Height = Convert.ToDouble(temp[1])
            };
            return c;
        }
    }
}

​ newly build xaml:【Window1.xaml】

<Window x:Class="WpfApp1.TypeConverterDemo.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1.TypeConverterDemo"
        mc:Ignorable="d"
        Title="Window1" Height="450" Width="800">
    <Grid>
        <local:ControlProperty Value="12,34" x:Name="cc"></local:ControlProperty>
        <Button Content=" Submit " Click="Button_Click"></Button>
    </Grid>
</Window>

Window1.xaml.cs Button Triggered events

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApp1.TypeConverterDemo
{
    /// <summary>
    /// Window1.xaml  Interaction logic of 
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            _ = this.cc.Value;
        }
    }
}

原网站

版权声明
本文为[@@Mr.Fu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206250915502374.html