Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the WPF dependency attribute

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "how to use WPF dependency attributes". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to use WPF dependency attributes" can help you solve the problem.

What are dependency attributes

A dependent property is one that can have no value of its own and can be fetched from other data sources through binding. Dependent properties support styling, data binding, inheritance, animation, and default values in WPF.

Setting all properties to dependent properties is not always the right solution, depending on its application scenario. Sometimes, the typical method of using private fields to implement properties can meet the requirements. The following scenarios for applying dependency attributes are given in MSDN:

1. You want to set properties in the style.

two。 You want the property to support data binding.

3. You want to be able to set properties using dynamic resource references.

4. You want to automatically inherit attribute values from the parent element in the element tree.

5. You want the attribute to be animated.

6. You want the property system to report when the property system, environment, or user performs actions or reads and uses styles to change the previous values of the properties.

7. You want to use established metadata conventions that are also used by the WPF process, such as reporting whether the layout system is required to rewrite visual objects of elements when changing property values.

2. Characteristics of dependent attributes 1. Notification of attribute changes

Whenever the value of a dependent attribute changes, wpf automatically triggers a series of actions based on the metadata of the attribute, which can re-render the UI element, update the current layout, refresh the data binding, and so on. One of the most interesting features of notification of this change is the attribute trigger, which can perform a series of custom actions when the attribute value changes. There is no need to change any other code to implement it. Demonstrate property change notification through the following example

Example: when you move the mouse over the Button button, the foreground color of the text changes to red, and when you leave, it becomes the default color of black, which is implemented in both traditional and dependent attributes:

(1) using the traditional way to implement, define MouseEnter and MouseLeave events on the Button button to deal with the mouse moving over the button and leaving, respectively. XAML interface code: when the mouse moves over the button, the foreground color turns red.

C# background code implementation:

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.Navigation;using System.Windows.Shapes Namespace WpfDemo {/ MainWindow.xaml interaction logic / public partial class MainWindow: Window {public MainWindow () {InitializeComponent () Move the mouse over the button / private void Button_MouseEnter (object sender, MouseEventArgs e) {Button btn = sender as Button; if (btn! = null) {btn.Foreground = Brushes.Red }} / mouse away button / private void Button_MouseLeave (object sender, MouseEventArgs e) {Button btn = sender as Button; if (btn! = null) {btn.Foreground = Brushes.Black } (2) implemented using dependent attributes, XAML interface code: move the mouse over it and the foreground color turns red

Using both of the above methods, you can change the foreground color of the Button button, and the effect is as follows:

When judging that the value of the attribute IsMouseOver is false, automatically change the value of Foreground to the previous value, so it is not necessary to change the value of Foreground to Black when writing the value of IsMouseOver to false.

2. Attribute value inheritance

Means that attribute values are passed down the element tree from the top down.

I use an inherited fontsize. I use my own fontsize.

Interface running effect:

3. Save memory space

Dependency properties and CLR properties are very different in memory use, and each CLR property contains a non-static field, so when we instantiate a type, we create all the CLR properties owned by that type, that is, the memory occupied by an object is determined when the new operation is instantiated, and wpf allows the object to be created without the space used to store data. Only retain the ability to obtain this default value when data is needed, that is, the ability to use other object data or allocate space in real time.

Third, how to customize dependency attributes

1. declare dependent attribute variables. Dependent properties are declared to expose a static variable through public static, and the variable must be of type DependencyProperty

2. Register in the attribute system. Use the DependencyProperty.Register method to register dependent properties, or use the DependencyProperty.RegisterReadOnly method to register

3. Use .NET properties to wrap dependent properties

When implementing a property on a class, as long as the class is derived from DependencyObject, you can choose to mark the property with the DependencyProperty identifier, thus setting it as a dependent property. The syntax is as follows:

Public static DependencyProperty TextProperty; TextProperty = DependencyProperty.Register ("Text", / / attribute name typeof (string), / / attribute type typeof (TestDependencyPropertyWindow), / / owner of the attribute, that is, to register the attribute on that class new PropertyMetadata ("")); / / attribute default value public string Text {get {return (string) GetValue (TextProperty);} set {SetValue (TextProperty, value);}}

Example: customize a dependent attribute, the interface includes a TextBox and TextBlock,TextBlock above the font foreground color changes with the TextBox input color, if the input value in TextBox can be converted into color, TextBlock font foreground color will display the input color value, if not converted, display the default foreground color.

1. Add a WPF version of the user control to the current project, named "MyDependencyProperty", and customize a dependency property in the MyDependencyProperty.xaml.cs file: 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.Navigation. Interactive logic of using System.Windows.Shapes;namespace WpfDemo {/ MyDependencyProperty.xaml / public partial class MyDependencyProperty: UserControl {public MyDependencyProperty () {InitializeComponent ();} / / 1, declare dependent attribute variable public static readonly DependencyProperty MyColorProperty / / 2. Register static MyDependencyProperty () {MyColorProperty = DependencyProperty.Register ("MyColor", typeof (string), typeof (MyDependencyProperty), new PropertyMetadata ("Red", (s, e) = > {var mdp = s as MyDependencyProperty) in the property system If (mdp! = null) {try {var color = (Color) ColorConverter.ConvertFromString (e.NewValue.ToString ()); mdp.Foreground = new SolidColorBrush (color) } catch {mdp.Foreground = new SolidColorBrush (Colors.Black);})) } / / 3. Wrap dependent attributes with .NET attributes: the attribute name must be the same as the name at the time of registration, / / that is, the MyColor public string MyColor {get {return (string) GetValue (MyColorProperty) at the time of registration corresponding to the attribute name MyColor } set {SetValue (MyColorProperty, value);}

Quickly define shortcuts to dependent attributes:

Enter propdp and press the Tab key twice in a row to automatically generate syntax that defines dependent attributes. It's the same as typing cw and pressing the Tab key twice in a row to automatically generate Console.Write ().

Public int MyProperty {get {return (int) GetValue (MyPropertyProperty);} set {SetValue (MyPropertyProperty, value);}} / Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc... Public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register ("MyProperty", typeof (int), typeof (ownerclass), new PropertyMetadata (0)); 2. Add a dependency attribute TextBlock I am customized to MyDependencyProperty.xaml 3, reference the newly created user control in MainWindow.xaml, and add a TextBox to enter color values, and bind the custom dependency attribute MyColor to TextBox

The effect displayed in the design interface:

4. Running effect of the program:

Enter the correct color value in TextBox, and the foreground color will be displayed as the currently entered color:

Enter the wrong color value in TextBox, and the foreground color will be displayed as the default color:

This is the end of the content on "how to use WPF dependency attributes". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report