Search code examples
c#xamlxamarinbindingattached-properties

Bind in code to Bindable Attached Property


From official document:

The namespace declaration is then used when setting the attached property on a specific control, as demonstrated in the following XAML code example:

<Label Text="Label Shadow Effect" local:ShadowEffect.HasShadow="true" />

The equivalent C# code is shown in the following code example:

var label = new Label { Text = "Label Shadow Effect" }; ShadowEffect.SetHasShadow (label, true);

My question:

Which would be the equivalent C# code for the following XAML binding:

<Label Text="Label Shadow Effect" local:ShadowEffect.HasShadow="{Binding HasShadow}" />

Example scenario

I have a LongPressEffect that exposes an attached Bindable Property Command. The effect is attached to a Label as shown below:

<Label x:Name="LongPressLabel"
       Text="Long press me"
       effects:LongPressEffect.Command = "{Binding MyCommand}">
   <Label.Effects>
       <effects:LongPressEffect />
   </Label.Effects>
</Label>

How do I do the same binding on C# code?

Similar threads

Seems to be the same problem presented here. Any ideas?


Solution

  • Apparently this works for me:

    
    var label = new Label()
    {
        Text = "Long press me"
    };
    
    var longPressedEffect = new LongPressedEffect();
    label.Effects.Add(longPressedEffect);
    
    Binding binding = new Binding();
    binding.Path = nameof(MyCommand);
    binding.Mode = BindingMode.TwoWay;
    label.SetBinding(longPressedEffect.CommandProperty, binding);