MAUI中如何在Editor的Style内使用Behaviors?
问题
我要给当前页面的Editor控件做样式化,因为这个控件会被多次使用,所以打算写一个Style。我想在Style里添加Behaviors,目前直接给Editor手动加Behaviors的方式是正常工作的,现在想问能不能在指定的TestEditor Style里实现相同的EventToCommandBehavior配置。
常规实现代码(直接添加Behaviors):
<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代码(需要添加Behaviors的Style):
<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>
解决方案
可以在Style中实现这个Behavior配置,但要注意绑定的写法——因为Style是可复用的,直接用x:Reference可能会遇到作用域问题(比如引用的页面在Style定义的上下文里不可见),建议改用RelativeSource来定位页面的BindingContext,避免硬编码页面引用。
修改后的完整Style代码如下:
<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"> <Setter.Value> <toolkit:BehaviorCollection> <toolkit:EventToCommandBehavior EventName="Unfocused" Command="{Binding Source={RelativeSource AncestorType={x:Type views:TestEditorPage}}, Path=BindingContext.UnfocusedCommand}" CommandParameter="{Binding .}"/> </toolkit:BehaviorCollection> </Setter.Value> </Setter> </Style>
关键说明:
- 必须把Behavior放在
toolkit:BehaviorCollection中,因为Behaviors属性的类型是BehaviorCollection,不能直接放置单个Behavior。 - 将原来的
x:Reference替换为RelativeSource AncestorType,指定页面的类型(比如views:TestEditorPage),这样Style在任何使用该Editor的地方都能正确找到页面的BindingContext,复用性更强。 - 如果你的项目中允许
x:Reference在Style中正常工作(比如Style定义在页面内部而非全局资源),也可以保留原绑定写法,但RelativeSource的方式适配性更好。
内容的提问来源于stack exchange,提问作者Death_Dealer
相关产品推荐
相关产品推荐

