首页 > 解决方案 > 如何在我创建的 XAML 模板中切换开关时捕获?

问题描述

我有这个模板:

<?xml version="1.0" encoding="utf-8"?>
<StackLayout xmlns="http://xamarin.com/schemas/2014/forms"
              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
              xmlns:local="clr-namespace:Test;assembly=Test" 
              x:Class="Test.Templates.SwitchTemplate" 
              x:Name="this" >
    <Switch IsToggled="{Binding IsToggled, Source={x:Reference this}}" />
</StackLayout>

我的 CS 后端如下所示:         

public partial class SwitchTemplate : StackLayout
{
    public SwitchTemplate()
    {
        InitializeComponent();
    }
       
    public static readonly BindableProperty IsToggledProperty =
           BindableProperty.Create(
                nameof(IsToggled),
                typeof(bool),
                typeof(SwitchTemplate),
                default(bool));
        
    public bool IsToggled
    {
        get { return (bool)GetValue(IsToggledProperty); }
        set { SetValue(IsToggledProperty, value); }
    }
}

我想做的是在 XAML 的后端 CS 中调用一个方法,在切换状态更改时使用模板。

有人可以给我一些关于如何编码 XAML 模板、其后端 CS 和使用该模板的 XAML 的 CS 的建议,以便我可以在切换状态更改时执行一些操作吗?

标签: xamarinxamarin.forms

解决方案


尝试将此 (propertyChanged) 添加到您的 Create

public static readonly BindableProperty IsToggledProperty =
           BindableProperty.Create(
                nameof(IsToggled),
                typeof(bool),
                typeof(SwitchTemplate),
                default(bool),
                propertyChanged: PropertyChanged);

并添加此方法:

private static void PropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
    var control = (SwitchTemplate)bindable;
    //Do something :)
}

推荐阅读