几天前我开始学习 XAML,但我很难解决这个问题。
在 Xamarin Forms 中,我想创建一个用户控件,其中包含一个标签和一个按钮,并且能够从使用我的用户控件的另一个页面将命令绑定到 XAML 中的用户控件。
我目前遇到异常:
Xamarin.Forms.Xaml.XamlParseException:'位置 8:24。无法分配属性“Test1”:属性不存在,或不可分配,或值和属性之间的类型不匹配'
这是我目前正在尝试开始工作的简化版本。
我的自定义控件 XAML
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="App3.Controls.Control1">
<StackLayout>
<Button Command="{Binding Test1}" Text="Test"/>
</StackLayout>
</ContentView>
使用我的自定义控件 XAML 进行控制
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:App3"
xmlns:controls="clr-namespace:App3.Controls"
x:Class="App3.MainPage">
<controls:Control1 Test1="{Binding Test2}" />
</ContentPage>
我的自定义控件隐藏代码
using System.Windows.Input;
using Xamarin.Forms;
namespace App3.Controls
{
public partial class Control1 : ContentView
{
private static readonly BindableProperty controlProperty = BindableProperty.Create("Test1", typeof(ICommand), typeof(Control1), null);
public Control1()
{
InitializeComponent();
}
public ICommand Test1
{
get
{
return (ICommand)GetValue(controlProperty);
}
set
{
SetValue(controlProperty, value);
}
}
}
}
使用自定义控件查看页面模型
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using Xamarin.Forms;
namespace App3
{
public class MainPageViewModel : INotifyPropertyChanged
{
public MainPageViewModel()
{
this.Test2 = new Command(test);
}
public void test()
{
Application.Current.MainPage.DisplayAlert("it works", "it works", "it works");
}
public ICommand Test2
{
get; set;
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}