我已经这样定义了我的风格:
<ContentView.Resources>
<ResourceDictionary>
<Style TargetType="Entry" x:Key="IntegralEntryBehavior">
<Setter Property="Behaviors" Value="valid:EntryIntegerValidationBehavior"/>
</Style>
</ResourceDictionary>
</ContentView.Resources>
以及多个类似的条目:
<StackLayout Grid.Column="0" Grid.Row="0">
<Entry Style="{StaticResource IntegralEntryBehavior}"/>
</StackLayout>
如果我这样定义Entry行为,则会得到一个错误那that Entry.Behaviors property is readonly
,但可以定义行为而无需Style
在Entry内部使用如下属性:
<Entry.Behaviors>
<valid:EntryIntegerValidationBehavior/>
</Entry.Behaviors>
这些方法之间有什么区别?为什么只有第二种方法有效?是否可以修改第一种方法以使其起作用?我正在寻找一种比第二种方法更短的方法来定义每个条目的这种行为。
您可以在此处签出示例:
基本上,将附加属性添加到您的行为,然后将样式设置器的属性设置为该附加属性。Attached属性处理将自身添加到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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句