我想为我的当前页面创建样式化的编辑器。我用了几次所以我决定为这个元素编写样式并想知道如何在样式中使用行为。如果我像常规方式那样做,一切正常
<Editor Style="{StaticResource TestEditor}"/>
<Editor.Behaviors>
<toolkit:EventToCommandBehavior
EventName="Unfocused"
Command="{Binding Source={x:Reference TestEditorPage}, Path=BindingContext.UnfocusedCommand}"
CommandParameter="{Binding .}">
</toolkit:EventToCommandBehavior>
</Editor.Behaviors>
</Editor>
那么如果可能的话,如何以我的风格做同样的事情:
<Style x:Key="TestEditor"
TargetType="Editor">
<Setter Property="AutoSize" Value="TextChanges"/>
<Setter Property="Grid.Column" Value="1"/>
<Setter Property="Placeholder" Value="Enter question answer"/>
<Setter Property="Text" Value="{Binding Source={RelativeSource AncestorType={x:Type models:TestAnswerResponce}}, Path=Answer}"/>
<Setter Property="Behaviors">
<!-- Behavior -->
</Setter>
</Style>
但是,创建设置控件的 Behaviors 属性的样式是不可能的,因为该属性是只读的。解决方案是向控制添加和删除行为的行为类添加附加属性。
作为解决方法,您可以将附加属性的值设置为 EventToCommandBehavior。试试下面的代码:
首先,创建一个行为类,在其中添加一个附加属性。
public class MyEditorStyleBehavior : Behavior<Editor>
{
public static readonly BindableProperty AttachBehaviorProperty =
BindableProperty.CreateAttached("AttachBehavior", typeof(object), typeof(MyEditorStyleBehavior), null,propertyChanged: OnAttachBehaviorChanged);
public static object GetAttachBehavior(BindableObject view)
{
return (object)view.GetValue(AttachBehaviorProperty);
}
public static void SetAttachBehavior(BindableObject view, object value)
{
view.SetValue(AttachBehaviorProperty, value);
}
static void OnAttachBehaviorChanged(BindableObject view, object oldValue, object newValue)
{
Editor editor = view as Editor;
if (editor == null)
{
return;
}
EventToCommandBehavior attachBehavior = newValue as EventToCommandBehavior;
editor.Behaviors.Add(attachBehavior);
}
}
在 xaml 中,消费行为。 Style 中的 BindingContext 是页面的 ViewModel。所以不必使用相对绑定。
<Style x:Key="TestEditor" TargetType="Editor">
<Setter Property="AutoSize" Value="TextChanges"/>
<Setter Property="Placeholder" Value="Enter question answer"/>
<Setter Property="Text" Value="{Binding MyEditorText}"/>
<Setter Property="local:MyEditorStyleBehavior.AttachBehavior">
<Setter.Value>
<toolkit:EventToCommandBehavior EventName="Unfocused"
Command="{Binding UnfocusedCommand}"
CommandParameter="{Binding MyEditorText}"/>
</Setter.Value>
</Setter>
希望它有效。