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

1、创建继承自Button的控件(新建ContentPage,改为继承自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"

..........



//后台代码
private void LabelButton_Clicked(object sender, EventArgs e)
{
    ((LabelButton)sender).MyLabel.BackgroundColor = Color.DarkBlue;
}

你可能感兴趣的:(Xamarin,C#,xamarin,wpf)