首页 > 解决方案 > 在代码中绑定到可绑定的附加属性

问题描述

来自官方文档

然后在特定控件上设置附加属性时使用命名空间声明,如以下 XAML 代码示例所示:

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

等效的 C# 代码显示在以下代码示例中:

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 Property Command。效果附在a上Label,如下图:

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

如何在 C# 代码上执行相同的绑定?

相似主题

似乎与此处提出的问题相同。有任何想法吗?

标签: c#xamlxamarinbindingattached-properties

解决方案


According to this document, you can try the following code:

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

The equivalent Label in 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>

推荐阅读