烂翻译系列之MAUI——行为

.NET Multi-platform App UI (.NET MAUI) behaviors let you add functionality to user interface controls without having to subclass them. Instead, the functionality is implemented in a behavior class and attached to the control as if it was part of the control itself.

NET 多平台 App UI (. NET MAUI)行为允许您向用户界面控件添加功能,而无需对它们进行子类化。相反,该功能是在行为类中实现的,并附加到控件,就好像它是控件本身的一部分一样。

Behaviors enable you to implement code that you would normally have to write as code-behind, because it directly interacts with the API of the control in such a way that it can be concisely attached to the control and packaged for reuse across more than one application. They can be used to provide a full range of functionality to controls, such as:

行为使您能够实现通常必须作为代码隐藏编写的代码,因为它直接与控件的 API 交互,从而可以简洁地附加到控件并打包以便在多个应用程序中重用。它们可用于为控件提供全面的功能,例如:

  • Adding an email validator to an Entry.  向Entry控件添加电子邮件验证器。
  • Creating a rating control using a tap gesture recognizer.  使用点击手势识别器创建评级控件。
  • Controlling an animation.  控制动画。

.NET MAUI supports two different types of behaviors:  NET MAUI 支持两种不同类型的行为:

  • Attached behaviors are static classes with one or more attached properties. For more information about attached behaviors, see Attached behaviors.  附加行为是具有一个或多个附加属性的静态类。有关附加行为的更多信息,请参见Attached behaviors
  • .NET MAUI behaviors are classes that derive from the Behavior or Behavior<T> class, where T is the type of the control to which the behavior should apply. For more information, see .NET MAUI Behaviors.  .NET MAUI 行为是从 Behavior 或 Behavior < T > 类派生的类,其中 T 是应用行为的控件的类型。有关更多信息,请参见.NET MAUI Behaviors

Attached behaviors

附加行为

Attached behaviors are static classes with one or more attached properties. An attached property is a special type of bindable property. They are defined in one class but attached to other objects, and they are recognizable in XAML as attributes that contain a class and a property name separated by a period. For more information about attached properties, see Attached properties.

附加行为是具有一个或多个附加属性的静态类。 附加属性是特殊的可绑定属性。 附加属性在一个类中定义,但附加到其他对象,它们在 XAML 中表现为包含类和属性名的属性,它们之间用.来分隔。 有关附加属性的详细信息,请参阅 附加属性

An attached property can define a propertyChanged delegate that will be executed when the value of the property changes, such as when the property is set on a control. When the propertyChanged delegate executes, it's passed a reference to the control on which it is being attached, and parameters that contain the old and new values for the property. This delegate can be used to add new functionality to the control that the property is attached to by manipulating the reference that is passed in, as follows:

附加属性可以定义一个 propertyChanged 委托,该委托将在属性值更改时执行,例如在控件上设置属性时执行。当 PropertyChanged 委托执行时,它将传递一个对所附加控件的引用,以及包含属性的新旧值的参数。此委托可用于通过操作传入的引用向附加属性的控件添加新功能,如下所示:

  1. The propertyChanged delegate casts the control reference, which is received as a BindableObject, to the control type that the behavior is designed to enhance.  propertyChanged 委托将控件引用(接收为 BindableObject)强制转换为旨在增强行为的控件类型。
  2. The propertyChanged delegate modifies properties of the control, calls methods of the control, or registers event handlers for events exposed by the control, to implement the core behavior functionality.  propertyChanged 委托修改控件属性、调用控件方法,或为控件公开的事件注册事件处理程序,以实现核心行为功能。

Warning  警告

Attached behaviors are defined in a static class, with static properties and methods. This makes it difficult to create attached behaviors that have state.

附加行为在类中 static 定义,其中包含 static 属性和方法。 这使得创建具有状态的附加行为变得困难。


 

Create an attached behavior

创建附加行为

An attached behavior can be implemented by creating a static class that contains an attached property that specifies a propertyChanged delegate.

可以通过创建包含指定 propertyChanged 委托的附加属性的静态类来实现附加行为。

The following example shows the AttachedNumericValidationBehavior class, which highlights the value entered by the user into an Entry control in red if it's not a double:

下面的示例显示 AttachedNumericValidationBehavior 类,该类高亮显示用户输入到Entry 控件中的值(如果不是 double 类型,则为红色):

 1 public static class AttachedNumericValidationBehavior
 2 {
 3     public static readonly BindableProperty AttachBehaviorProperty =
 4         BindableProperty.CreateAttached("AttachBehavior", typeof(bool), typeof(AttachedNumericValidationBehavior), false, propertyChanged: OnAttachBehaviorChanged);
 5 
 6     public static bool GetAttachBehavior(BindableObject view)
 7     {
 8         return (bool)view.GetValue(AttachBehaviorProperty);
 9     }
10 
11     public static void SetAttachBehavior(BindableObject view, bool value)
12     {
13         view.SetValue(AttachBehaviorProperty, value);
14     }
15 
16     static void OnAttachBehaviorChanged(BindableObject view, object oldValue, object newValue)
17     {
18         Entry entry = view as Entry;
19         if (entry == null)
20         {
21             return;
22         }
23 
24         bool attachBehavior = (bool)newValue;
25         if (attachBehavior)
26         {
27             entry.TextChanged += OnEntryTextChanged;
28         }
29         else
30         {
31             entry.TextChanged -= OnEntryTextChanged;
32         }
33     }
34 
35     static void OnEntryTextChanged(object sender, TextChangedEventArgs args)
36     {
37         double result;
38         bool isValid = double.TryParse(args.NewTextValue, out result);
39         ((Entry)sender).TextColor = isValid ? Colors.Black : Colors.Red;
40     }
41 }

In this example, the AttachedNumericValidationBehavior class contains an attached property named AttachBehavior with a static getter and setter, which controls the addition or removal of the behavior to the control to which it will be attached. This attached property registers the OnAttachBehaviorChanged method that will be executed when the value of the property changes. This method registers or de-registers an event handler for the TextChanged event, based on the value of the AttachBehavior attached property. The core functionality of the behavior is provided by the OnEntryTextChanged method, which parses the value entered in the Entry and sets the TextColor property to red if the value isn't a double.

在这个例子中,AttachedNumericValidationBehavior 类包含一个名为 AttachBehavior 的附加属性,该属性带有一个静态 getter 和 setter,用于控制向控件添加或删除行为。此附加属性注册了 OnAttachBehaviorChanged 方法,该方法将在该属性的值更改时执行。此方法根据 AttachBehavior 附加属性的值为 TextChanged 事件注册或取消注册事件处理程序。行为的核心功能由 OnEntryTextChanged 方法提供,该方法解析在 Entry 中输入的值,如果值不是 double类型,则将 TextColor 属性设置为红色。

Consume an attached behavior

使用附加行为

An attached behavior can be consumed by setting its attached property on the target control.

可以通过在目标控件上设置附加属性来使用附加行为。

The following example shows consuming the AttachedNumericValidationBehavior class on an Entry by adding the AttachBehavior attached property to the Entry:

下面的示例演示如何通过将 AttachBehavior 附加属性添加到 Entry 来在Entry 上使用 AttachedNumericValidationBehavior 类:

1 <ContentPage ...
2              xmlns:local="clr-namespace:BehaviorsDemos">
3     <Entry Placeholder="Enter a System.Double" local:AttachedNumericValidationBehavior.AttachBehavior="true" />
4 </ContentPage>

The equivalent Entry in C# is shown in the following code example:

下面的代码示例显示了 C # 中等效的 Entry:

1 Entry entry = new Entry { Placeholder = "Enter a System.Double" };
2 AttachedNumericValidationBehavior.SetAttachBehavior(entry, true);

The following screenshot shows the attached behavior responding to invalid input:

下面的屏幕截图显示了对无效输入的响应行为:

 


 

Note  注意

Attached behaviors are written for a specific control type (or a superclass that can apply to many controls), and they should only be added to a compatible control.

附加的行为是为特定的控件类型(或者某个超类控件,这样就可以将行为附加到多种控件中)编写的,它们应该只添加到兼容控件中。


 

Remove an attached behavior

移除附加行为

The AttachedNumericValidationBehavior class can be removed from a control by setting the AttachBehavior attached property to false:

通过将 AttachBehavior 附加属性设置为 false,可以从控件中移除 AttachedNumericValidationBehavior 类:

1 <Entry Placeholder="Enter a System.Double" local:AttachedNumericValidationBehavior.AttachBehavior="false" />

At runtime, the OnAttachBehaviorChanged method will be executed when the value of the AttachBehavior attached property is set to false. The OnAttachBehaviorChanged method will then de-register the event handler for the TextChanged event, ensuring that the behavior isn't executed as you interact with the control.

在运行时,如果 AttachBehavior 附加属性的值设置为 false 时,则将执行 OnAttachBehaviorChanged 方法。 然后,OnAttachBehaviorChanged方法将取消注册TextChanged 事件的事件处理程序 ,确保在使用控件是时不会执行该行为。

.NET MAUI behaviors

.NET MAUI 行为

.NET MAUI behaviors are created by deriving from the Behavior or Behavior<T> class.

.NET MAUI 行为是通过Behavior 或Behavior < T > 类派生而来的。

The process for creating a .NET MAUI behavior is as follows:

创建.NET MAUI 行为的过程如下:

  1. Create a class that inherits from the Behavior or Behavior<T> class, where T is the type of the control to which the behavior should apply.  创建一个继承自 Behavior 或 Behavior<T> 类的子类,其中 T 是行为将应用到的控件类型。
  2. Override the OnAttachedTo method to perform any required setup.  重写OnAttachedTo 方法来执行任何所需的设置。
  3. Override the OnDetachingFrom method to perform any required cleanup.  重写 OnDetachingFrom 方法以执行任何所需的清理。
  4. Implement the core functionality of the behavior.  实现行为的核心功能。

This results in the structure shown in the following example:

这就产生了下列示例所示的结构:

 1 public class MyBehavior : Behavior<View>
 2 {
 3     protected override void OnAttachedTo(View bindable)
 4     {
 5         base.OnAttachedTo(bindable);
 6         // Perform setup
 7     }
 8 
 9     protected override void OnDetachingFrom(View bindable)
10     {
11         base.OnDetachingFrom(bindable);
12         // Perform clean up
13     }
14 
15     // Behavior implementation
16 }

The OnAttachedTo method is called immediately after the behavior is attached to a control. This method receives a reference to the control to which it is attached, and can be used to register event handlers or perform other setup that's required to support the behavior functionality. For example, you could subscribe to an event on a control. The behavior functionality would then be implemented in the event handler for the event.

OnAttachedTo 方法在行为附加到控件之后立即被调用。此方法接收被附加到的控件的引用,用来注册事件处理程序或执行其他支持行为功能所需的设置。例如,您可以订阅控件上的一个事件。然后在事件处理程序中实现行为功能。

The OnDetachingFrom method is called when the behavior is removed from the control. This method receives a reference to the control to which it is attached, and is used to perform any required cleanup. For example, you could unsubscribe from an event on a control to prevent memory leaks.

从控件中移除行为时调用 OnDetachingFrom 方法。此方法接收被附加到的控件的引用,用来执行任何必要的清理。例如,您可以取消订阅控件上的事件,以防止内存泄漏。

The behavior can then be consumed by attaching it to the Behaviors collection of the control.

然后,可以通过将该行为附加到控件的 Behavior 集合来使用该行为。

Create a .NET MAUI Behavior

Create a .NET MAUI 行为

A .NET MAUI behavior can be implemented by creating a class that derives from the Behavior or Behavior<T> class, and overriding the OnAttachedTo and OnDetachingFrom methods.

.NET MAUI 行为可以通过以下方式实现: 创建一个从 Behavior 或 Behavior<T>类派生的类,并重写 OnAttachedTo 和 OnDetachingFrom 方法。

The following example shows the NumericValidationBehavior class, which highlights the value entered by the user into an Entry control in red if it's not a double:

下面的示例显示 NumericValidationBehavior 类,该类突出显示用户输入到 Entry 控件中的值(如果不是 double类型,则显示为红色):

 1 public class NumericValidationBehavior : Behavior<Entry>
 2 {
 3     protected override void OnAttachedTo(Entry entry)
 4     {
 5         entry.TextChanged += OnEntryTextChanged;
 6         base.OnAttachedTo(entry);
 7     }
 8 
 9     protected override void OnDetachingFrom(Entry entry)
10     {
11         entry.TextChanged -= OnEntryTextChanged;
12         base.OnDetachingFrom(entry);
13     }
14 
15     void OnEntryTextChanged(object sender, TextChangedEventArgs args)
16     {
17         double result;
18         bool isValid = double.TryParse(args.NewTextValue, out result);
19         ((Entry)sender).TextColor = isValid ? Colors.Black : Colors.Red;
20     }
21 }

In this example, the NumericValidationBehavior class derives from the Behavior<T> class, where T is an Entry. The OnAttachedTo method registers an event handler for the TextChanged event, with the OnDetachingFrom method de-registering the TextChanged event to prevent memory leaks. The core functionality of the behavior is provided by the OnEntryTextChanged method, which parses the value entered in the Entry and sets the TextColor property to red if the value isn't a double.

在这个示例中,NumericValidationBehavior 类派生自 Behavior<T>类,其中 T 是Entry类型。OnAttachedTo 方法为 TextChanged 事件注册一个事件处理程序,OnDeta*类型chingFrom 方法取消注册 TextChanged 事件以防止内存泄漏。行为的核心功能由 OnEntryTextChanged 方法提供,该方法解析在 Entry 中输入的值,如果值不是 double,则将 TextColor 属性设置为红色。


 

 Important  重要

.NET MAUI does not set the BindingContext of a behavior, because behaviors can be shared and applied to multiple controls through styles.

.NET MAUI 不设置行为的 BindingContext,因为行为可以通过样式共享并应用于多个控件。


 

Consume a .NET MAUI behavior

使用.NET MAUI行为

Every .NET MAUI control has a Behaviors collection, to which one or more behaviors can be added:

每个.NET MAUI 控件都有一个 Behaviors 集合,在其中可以添加一个或多个行为:

<Entry Placeholder="Enter a System.Double">
    <Entry.Behaviors>
        <local:NumericValidationBehavior />
    </Entry.Behaviors>
</Entry>

The equivalent Entry in C# is shown in the following code example:

下面的代码示例显示了 C # 中等效的 Entry:

1 Entry entry = new Entry { Placeholder = "Enter a System.Double" };
2 entry.Behaviors.Add(new NumericValidationBehavior());

The following screenshot shows the .NET MAUI behavior responding to invalid input:

下面的屏幕截图显示了对无效输入的响应行为:

 


 

Warning  警告

.NET MAUI behaviors are written for a specific control type (or a superclass that can apply to many controls), and they should only be added to a compatible control. Attempting to attach a .NET MAUI behavior to an incompatible control will result in an exception being thrown.

.NET MAUI 行为是为特定的控件类型(或者可以应用于许多控件的超类)编写的,它们应该只添加到兼容控件中。尝试将.NETMAUI 行为附加到不兼容的控件将导致引发异常。


 

Consume a .NET MAUI behavior with a style

通过样式使用.NET MAUI 行为

.NET MAUI behaviors can be consumed by an explicit or implicit style. However, creating a style that sets the Behaviors property of a control is not possible because the property is read-only. The solution is to add an attached property to the behavior class that controls adding and removing the behavior. The process is as follows:

.NET MAUI 行为可以通过显式或隐式样式使用。但是,不可能创建设置控件的 Behaviors  属性的样式,因为该属性是只读的。解决方案是向控件添加和移除行为的行为类添加一个附加属性。过程如下:

  1. Add an attached property to the behavior class that will be used to control the addition or removal of the behavior to the control to which the behavior will be attached. Ensure that the attached property registers a propertyChanged delegate that will be executed when the value of the property changes.  将附加属性添加到行为类中,该属性将用于控制将该行为添加或移除到控件中。确保附加的属性注册一个 PropertyChanged 委托,该委托将在属性值更改时执行。
  2. Create a static getter and setter for the attached property.  为附加属性创建静态 getter 和 setter。
  3. Implement logic in the propertyChanged delegate to add and remove the behavior.  在 PropertyChanged 委托中实现逻辑以添加和删除行为。

The following example shows the NumericValidationStyleBehavior class, which has an attached property that controls adding and removing the behavior:

下面的示例演示 NumericValidationStyleBehavior 类,该类具有一个附加属性,用于控制添加和移除行为:

 1 public class NumericValidationStyleBehavior : Behavior<Entry>
 2 {
 3     public static readonly BindableProperty AttachBehaviorProperty =
 4         BindableProperty.CreateAttached("AttachBehavior", typeof(bool), typeof(NumericValidationStyleBehavior), false, propertyChanged: OnAttachBehaviorChanged);
 5 
 6     public static bool GetAttachBehavior(BindableObject view)
 7     {
 8         return (bool)view.GetValue(AttachBehaviorProperty);
 9     }
10 
11     public static void SetAttachBehavior(BindableObject view, bool value)
12     {
13         view.SetValue(AttachBehaviorProperty, value);
14     }
15 
16     static void OnAttachBehaviorChanged(BindableObject view, object oldValue, object newValue)
17     {
18         Entry entry = view as Entry;
19         if (entry == null)
20         {
21             return;
22         }
23 
24         bool attachBehavior = (bool)newValue;
25         if (attachBehavior)
26         {
27             entry.Behaviors.Add(new NumericValidationStyleBehavior());
28         }
29         else
30         {
31             Behavior toRemove = entry.Behaviors.FirstOrDefault(b => b is NumericValidationStyleBehavior);
32             if (toRemove != null)
33             {
34                 entry.Behaviors.Remove(toRemove);
35             }
36         }
37     }
38     ...
39 }

In this example, the NumericValidationStyleBehavior class contains an attached property named AttachBehavior with a static getter and setter, which controls the addition or removal of the behavior to the control to which it will be attached. This attached property registers the OnAttachBehaviorChanged method that will be executed when the value of the property changes. This method adds or removes the behavior to the control, based on the value of the AttachBehavior attached property.

在这个示例中,NumericValidationStyleBehavior 类包含一个名为 AttachBehavior 的附加属性,该属性带有一个静态 getter 和 setter,用于控制向控件添加或删除行为。此附加属性注册 OnAttachBehaviorChanged 方法,该方法将在该属性的值更改时执行。此方法基于 AttachBehavior 附加属性的值向控件添加或移除行为。

The following code example shows an explicit style for the NumericValidationStyleBehavior that uses the AttachBehavior attached property, and which can be applied to Entry controls:

下面的代码示例显示 NumericValidationStyleBehavior 的显式样式,该样式使用 AttachBehavior 附加属性,可应用于 Entry 控件:

1 <Style x:Key="NumericValidationStyle" TargetType="Entry">
2     <Style.Setters>
3         <Setter Property="local:NumericValidationStyleBehavior.AttachBehavior" Value="true" />
4     </Style.Setters>
5 </Style>

The Style can be applied to an Entry by setting its Style property to the style using the StaticResource markup extension:

通过使用 StaticResource 标记扩展将其 Style 属性设置为样式,可以将 Style 应用于 Entry:

1 <Entry Placeholder="Enter a System.Double" Style="{StaticResource NumericValidationStyle}">

For more information about styles, see Styles.

有关样式的详细信息,请参阅Styles


Note  注意

While you can add bindable properties to a behavior that is set or queried in XAML, if you do create behaviors that have state they should not be shared between controls in a Style in a ResourceDictionary.

虽然您可以向行为(在XAML中设置或查询的行为)添加可绑定属性,但是,如果您创建具有状态的行为,则不应在ResourceDictionary中的Style中共享它们。


 

Remove a .NET MAUI behavior

移除.NET MAUI 行为

The OnDetachingFrom method is called when a behavior is removed from a control, and is used to perform any required cleanup such as unsubscribing from an event to prevent a memory leak. However, behaviors are not implicitly removed from controls unless the control's Behaviors collection is modified by the Remove or Clear method:

当从控件中移除行为时调用 OnDetachingFrom 方法,该方法用于执行任何所需的清理,例如从事件中取消订阅,以防止内存泄漏。然而,行为不会从控件中隐式移除,除非控件的Behaviors 集合通过Remove 或Clear 方法进行了修改:

1 Behavior toRemove = entry.Behaviors.FirstOrDefault(b => b is NumericValidationStyleBehavior);
2 if (toRemove != null)
3 {
4     entry.Behaviors.Remove(toRemove);
5 }

Alternatively, the control's Behaviors collection can be cleared:

或者,可以清除控件的 Behaviors 集合:

1 entry.Behaviors.Clear();

 

Note  注意

.NET MAUI behaviors are not implicitly removed from controls when pages are popped from the navigation stack. Instead, they must be explicitly removed prior to pages going out of scope.

当页从导航堆栈中弹出时,NET MAUI 行为不会从控件中隐式移除。相反,必须在页面超出作用域之前显式删除它们。


 

posted @ 2022-12-20 12:25  菜鸟吊思  阅读(191)  评论(0)    收藏  举报