官术网_书友最值得收藏!

Attached properties

Another way to implement behaviors in order to modify default control behavior is to use attached properties to declare a bindable extension to existing controls. This approach is generally used for small behavioral adjustments, such as enabling/disabling other behaviors, as well as adding/removing effects. Let's get started:

  1. In order to implement such a behavior, we need to create a bindable property that will be used on other controls:
 public static class Validations
{
public static readonly BindableProperty ValidateRequiredProperty =
BindableProperty.CreateAttached(
"ValidateRequired",
typeof(bool),
typeof(RequiredValidation),
false,
propertyChanged: OnValidateRequiredChanged);

public static bool GetValidateRequired(BindableObject view)
{
return (bool)view.GetValue(ValidateRequiredProperty);
}

public static void SetValidateRequired(BindableObject view,
bool value)
{
view.SetValue(ValidateRequiredProperty, value);
}

private static void OnValidateRequiredChanged(
BindableObject bindable, object oldValue, object
newValue)
{
// TODO:
}
}
  1. In the case of attached behaviors, the static class can be directly accessed so that it sets the attached property on the current control (instead of creating and adding a behavior):
 <Entry x:Name="usernameEntry" Placeholder="username" 
Text="{Binding UserName, Mode=OneWayToSource}"
behaviors:Validations.ValidateRequired="true" >
  1. By implementing the ValidateRequired property changed handler, we can have the attached property insert and remove the required validation to various Entry views:
 private static void OnValidateRequiredChanged(
BindableObject bindable,
object oldValue,
object newValue)
{
if(bindable is Entry entry)
{
if ((bool)newValue)
{
entry.Behaviors.Add(new ValidationBehavior()
{
ValidationRule = new RequiredValidationRule()
});
}
else
{
var behaviorToRemove = entry.Behaviors
.OfType<ValidationBehavior>()
.FirstOrDefault(
item => item.ValidationRule is
RequiredValidationRule);


if (behaviorToRemove != null)
{
entry.Behaviors.Remove(behaviorToRemove);
}
}
}
}
主站蜘蛛池模板: 紫阳县| 双桥区| 仁布县| 三都| 古蔺县| 文水县| 高州市| 安徽省| 汝阳县| 孝感市| 永济市| 镇赉县| 金坛市| 什邡市| 舒城县| 资兴市| 贵州省| 策勒县| 嘉义县| 铁岭市| 壶关县| 虹口区| 鄂托克前旗| 瓮安县| 江津市| 西华县| 新田县| 拜泉县| 长岭县| 许昌市| 新巴尔虎右旗| 南安市| 赞皇县| 黄大仙区| 芒康县| 新乡县| 垣曲县| 吴川市| 张家口市| 富平县| 虞城县|