(Xamarin)Xaml以控件作为参数传递

1、创建继承自Button的控件(新建ContentPage,改为继承自Button)

<!--LabelButton.xaml-->
<?xml version="1.0" encoding="utf-8" ?>
<Button xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App1.Controls.LabelButton">
</Button>

2、创建Label类型的BindableProperty属性,可以将页面的Label控件传递进来

//LabelButton.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace App1.Controls
{
    //[XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class LabelButton : Button
    {
        //Bindable属性,类似WPF的依赖属性,属性名需要符合常规属性名+Property的格式
        public static readonly BindableProperty MyLabelProperty = BindableProperty.Create(nameof(MyLabel), typeof(Label), typeof(LabelButton));
        
        public Label MyLabel
        {
            get { return (Label)GetValue(MyLabelProperty); }
            set { SetValue(MyLabelProperty, value); }
        }
        
        public LabelButton()
        {
            InitializeComponent();
        }
    }
}

3、在使用代码中,Xaml通过x:Reference引用传递Label控件

<!--引入命名空间-->
xmlns:controls="clr-namespace:App1.Controls"

..........


<!--调用空间并传入Label属性-->
<Label x:Name="lblEventTrigger" Text="属性测试" VerticalTextAlignment="Center" HorizontalTextAlignment="Center" BackgroundColor="LightSteelBlue"/>

<controls:LabelButton Text="改变Label颜色" MyLabel="{Binding Source={x:Reference lblEventTrigger}}" Clicked="LabelButton_Clicked"/>
//后台代码
private void LabelButton_Clicked(object sender, EventArgs e)
{
    ((LabelButton)sender).MyLabel.BackgroundColor = Color.DarkBlue;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值