当前位置:网站首页>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;
}
}
}
边栏推荐
- How much does a wechat applet cost? Wechat applet development and production costs? Come and have a look
- Android database security: after the user exits, the transaction rollback log still stores relevant data information
- Best producer consumer code
- Comparison and evaluation of digicert and globalsign single domain ov SSL certificates
- Tiktok brand goes to sea: both exposure and transformation are required. What are the skills of information flow advertising?
- Macro application connector\
- Pytorch_ Geometric (pyg) uses dataloader to report an error runtimeerror: sizes of tenants must match except in dimension 0
- tokenizers>=0.11.1,!= 0.11.3,<0.13 is required for a normal functioning of this module,
- Houdini图文笔记:Your driver settings have been set to force 4x Antialiasing in OpenGL applications问题的解决
- 链表 删除链表中的节点
猜你喜欢
Flutter dialog: cupertinoalertdialog
我希望按照我的思路盡可能將canvas基礎講明白
Minio基本使用与原理
Jetpack compose layout (IV) - constraintlayout
【动态规划】—— 数字三角形
Basic use and cluster construction of consult
Shardingsphere proxy 4.1 sub database and sub table
【论文阅读|深读】LINE: Large-scale Information Network Embedding
Basic usage and principle of schedulemaster distributed task scheduling center
Tiktok brand goes to sea: both exposure and transformation are required. What are the skills of information flow advertising?
随机推荐
Houdini图文笔记:Could not create OpenCL device of type (HOUDINI_OCL_DEVICETYPE)问题的解决
The path of Architects
How much does a wechat applet cost? Wechat applet development and production costs? Come and have a look
Tiktok brand goes to sea: both exposure and transformation are required. What are the skills of information flow advertising?
Linked list delete nodes in the linked list
[paper reading | deep reading] line: large scale information network embedding
[dynamic planning] - Digital triangle
Can two Mitsubishi PLC adopt bcnettcp protocol to realize wireless communication of network interface?
Kotlin keyword and operator
Identityserver4 definition concept
Flask blog practice - realize personal center and authority management
【OpenCV 例程200篇】210. 绘制直线也会有这么多坑?
在Microsoft Exchange Server 2007中安装SSL证书的教程
String longest common prefix
SparseArray details
manhattan_ Slam environment configuration
The title of my composition is - "my district head father"
Pytorch_ Geometric (pyg) uses dataloader to report an error runtimeerror: sizes of tenants must match except in dimension 0
Flask博客实战 - 实现侧边栏最新文章及搜索
WebApi性能优化