Avalonia.Xaml.Behaviors 用法记录

在Avalonia里使用 Avalonia.Xaml.Behaviors

闲话不多说开始。
之前的版本一直都是使用

  xmlns:i="clr-namespace:Avalonia.Xaml.Interactivity;assembly=Avalonia.Xaml.Interactivity"
  xmlns:ia="clr-namespace:Avalonia.Xaml.Interactions.Core;assembly=Avalonia.Xaml.Interactions.Core"
<i:Interaction.Behaviors>
 	xxx
</i:Interaction.Behaviors>

<i:Interaction.Triggers>
  <i:EventTrigger EventName="LostFocus">
      <i:InvokeCommandAction Command="{Binding LostFocusCommand}" />
  </i:EventTrigger>
</i:Interaction.Triggers>

这样去使用。

但新版本没必要这么写。

直接使用 Interaction.Behaviors

例如我需要让 textbox 的IsVisible 为true 时 获取焦点并 选中全部。在失去焦点事隐藏

写了一个额外的helper.

public class FocusOnVisibleBehavior  : Behavior<TextBox>
{
    
    protected override void OnAttached()
    {
        base.OnAttached();

        if (AssociatedObject != null)
        {
            // 监听 IsVisible 属性的变化
            AssociatedObject.PropertyChanged += OnPropertyChanged!;
        }
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();

        if (AssociatedObject != null)
        {
            // 移除事件监听
            AssociatedObject.PropertyChanged -= OnPropertyChanged!;
        }
    }

    private void OnPropertyChanged(object sender, AvaloniaPropertyChangedEventArgs e)
    {
        if (e.Property != Visual.IsVisibleProperty) return;
        if (AssociatedObject is not { IsVisible: true }) return;
        // 设置焦点
        AssociatedObject.Focus();

        // 全选文本内容
        AssociatedObject.SelectAll();
    }
}
public void LostFocus()
 {
     IsEdit = !IsEdit;
 }
    

在文件中引入

 xmlns:helper="using:AvaloniaScrapy.Helper"

然后直接写就可以了。

<TextBox IsVisible="{Binding IsEdit}" Text="{Binding Name}">
     <Interaction.Behaviors>
         <helper:FocusOnVisibleBehavior />
         <EventTriggerBehavior EventName="LostFocus">
             <InvokeCommandAction Command="{Binding LostFocus}"/>
         </EventTriggerBehavior>
     </Interaction.Behaviors>
 </TextBox>

完成。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值