如何在行为中绑定属性? [英] How to binding property in a behavior?

查看:24
本文介绍了如何在行为中绑定属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个使用电话掩码的行为.当显式插入掩码时,它工作正常.但是当我在选择器中更改电话类型时,我想与视图模型通信以更改掩码.

I created a behavior to use a phone mask. It is working properly, when the Mask is inserted explicitly. But I would like to communicate with the view model to change the mask, when I change the type of phone in the picker.

在 xaml 文件中:

In xaml file:

<Picker 
      x:Name="picker_cadastronotificacao_tipotelefone" 
      Title="{x:Static local:AppResources.picker_cadastronotificacao_tipotelefone}"
      Style="{StaticResource Picker}"
      SelectedItem="{Binding TipoTelefoneSelecionado}">
      <Picker.Items>
             <x:String>Celular</x:String>
             <x:String>Telefone Fixo</x:String>
      </Picker.Items>
</Picker>


<Entry 
      x:Name="entry_cadastronotificacao_telefone" 
      Placeholder="{x:Static local:AppResources.entry_cadastronotificacao_telefone}" 
      Style="{StaticResource EntradasTexto}" 
      Text="{Binding Telefone}"
      Keyboard="Telephone"
      IsEnabled="{Binding HabilitarCampoTelefone}">

      <Entry.Behaviors>
             <behavior:MaskBehavior Mascara="{Binding MascaraTelefone}"/>
      </Entry.Behaviors>
</Entry>

在视图模型中:

if (TipoTelefoneSelecionado == "Telefone Fixo")
      MascaraTelefone = "(XX) XXXX - XXXX";
else if(TipoTelefoneSelecionado == "Celular")
      MascaraTelefone = "(XX) XXXXX - XXXX";

错误:找不到睫​​毛膏"的属性、可绑定属性或事件,或者值和属性之间的类型不匹配.

Error: No property, bindable property, or event found for 'Mascara', or mismatching type between value and property.

推荐答案

您需要使 MaskBehavior.Mascara 属性成为可绑定属性(而不是常规"属性.

You need to make the MaskBehavior.Mascara property a bindable property (as opposed to a "regular" property.

也就是说,在 MaskBehavior 中而不是这样:

That is, in MaskBehavior instead of this:

public string Mascara { get; set; }

这样做:

public static readonly BindableProperty MascaraProperty = BindableProperty.Create(
                nameof(Mascara),
                typeof(MaskBehavior),
                typeof(string));

public string Mascara
{
    get => (string) GetValue(MascaraProperty);
    set => SetValue(MascaraProperty, value);
}

这篇关于如何在行为中绑定属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆