将代码绑定到 Bindable Attached 属性

Bind in code to Bindable Attached Property

来自官方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);

我的问题:

以下 XAML 绑定的等效 C# 代码:

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

示例场景

我有一个 LongPressEffect 公开了附加的 Bindable 属性 Command。效果附加一个Label如下图:

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

如何对 C# 代码进行相同的绑定?

相似线程

似乎出现了相同的问题 here。有什么想法吗?

根据this document,你可以试试下面的代码:

        label1.Effects.Add(new LongPressedEffect());
        LongPressedEffect.SetCommand(label1,mycommand);

C# 中的等效标签

   <Label
        x:Name="label1"
        effects:LongPressedEffect.Command="{Binding command1}"
        effects:LongPressedEffect.CommandParameter="{Binding .}"
        BackgroundColor="Red"
        Text="Long Press Me!">
        <Label.Effects>
            <effects:LongPressedEffect />
        </Label.Effects>
    </Label>

显然这对我有用:


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);