【问题标题】:Setting Entry Behaviors using Style attribute使用 Style 属性设置条目行为
【发布时间】:2020-10-04 14:01:27
【问题描述】:

我已经这样定义了我的风格:

<ContentView.Resources>
    <ResourceDictionary>
        <Style TargetType="Entry" x:Key="IntegralEntryBehavior">
            <Setter Property="Behaviors" Value="valid:EntryIntegerValidationBehavior"/>
        </Style>
    </ResourceDictionary>
</ContentView.Resources>

还有多个类似的Entries:

<StackLayout Grid.Column="0" Grid.Row="0">
    <Entry Style="{StaticResource IntegralEntryBehavior}"/>
</StackLayout>

如果我像这样定义 Entry 行为,我会收到一个错误,即 Entry.Behaviors property is readonly,但可以在不使用 Entry 中的 Style 属性的情况下定义行为:

<Entry.Behaviors>
    <valid:EntryIntegerValidationBehavior/>
</Entry.Behaviors>

这些方法有什么区别?为什么只有第二种方法有效?是否可以修改第一种方法以使其工作?我正在寻找一种比第二个选项更短的方法来为每个条目定义此行为。

【问题讨论】:

标签: xaml xamarin xamarin.forms


【解决方案1】:

您可以在此处查看示例:

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/behaviors/creating#consuming-a-xamarinforms-behavior-with-a-style

基本上,将附加属性添加到您的行为中,然后将样式设置器的属性设置为该附加属性。附加属性处理将自身添加到您附加到的Entry

public class EntryIntegerValidationBehavior : Behavior<Entry>
{
  public static readonly BindableProperty AttachBehaviorProperty =
    BindableProperty.CreateAttached ("AttachBehavior", typeof(bool), typeof(EntryIntegerValidationBehavior), false, propertyChanged: OnAttachBehaviorChanged);

  public static bool GetAttachBehavior (BindableObject view)
  {
    return (bool)view.GetValue (AttachBehaviorProperty);
  }

  public static void SetAttachBehavior (BindableObject view, bool value)
  {
    view.SetValue (AttachBehaviorProperty, value);
  }

  static void OnAttachBehaviorChanged (BindableObject view, object oldValue, object newValue)
{
    var entry = view as Entry;
    if (entry == null) {
        return;
    }

    bool attachBehavior = (bool)newValue;
    if (attachBehavior) {
        entry.Behaviors.Add (new EntryIntegerValidationBehavior ());
    } else {
        var toRemove = entry.Behaviors.FirstOrDefault (b => b is EntryIntegerValidationBehavior);
        if (toRemove != null) {
            entry.Behaviors.Remove (toRemove);
        }
    }
  }

  // Actual behavior code here

}

最后编辑你的样式,如下所示:

    <Style TargetType="Entry" x:Key="IntegralEntryBehavior">
        <Setter Property="valid:EntryIntegerValidationBehavior.AttachBehavior" Value="true"/>
    </Style>

【讨论】:

  • 如果传递任何附加值怎么办?创建另一个附加属性?
  • @MayurPaghdal 您可以创建一个新的附加属性或为附加属性分配一个更复杂的对象,该对象可以容纳的不仅仅是布尔值。
猜你喜欢
  • 2023-01-20
  • 2018-12-13
  • 1970-01-01
  • 1970-01-01
  • 2015-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多