How to binding property in a behavior?

人盡茶涼 提交于 2021-01-29 08:46:55

问题


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.

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>

In view model:

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.


回答1:


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

That is, in MaskBehavior instead of this:

public string Mascara { get; set; }

Do this:

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

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


来源:https://stackoverflow.com/questions/57060715/how-to-binding-property-in-a-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!