“我的自定义组件使用了 ViewModel / BindingContext。”
如果它是“独立的”,则创建可重用的自定义组件会更容易 - 没有 BindingContext。
构造函数:
public CustomComponent()
{
InitializeComponent();
}
将组件视图模型中当前拥有的所有内容移至 xaml.cs 代码隐藏文件中。
现在在 CustomComponent.xaml 中,为其命名(此处theComponent
):
<ContentView ...
x:Name="theComponent"
x:Class=...>
当组件的 xaml 想要绑定到其自身的属性时,这会派上用场:
<Label Text="{Binding TestString, Source={x:Reference theComponent}}" />
public string TestString
{
get => _testString;
set {
_testString = value;
OnPropertyChanged();
}
}
private string _testString = "test";
tl;dr:如果组件有一个x:Name="theComponent"
在它的xaml中,可以使用{Binding ..., Source={x:Reference theComponent}}
,来引用它自己的属性。不需要 BindingContext。
如果您希望组件具有关联的 ViewModel,则使用上述技术,您不必将 BindingContext 设置为该 VM。像这样做:
public class MyViewModel
{
public string TestString
{
get => _testString;
set {
_testString = value;
OnPropertyChanged();
}
}
private string _testString = "test";
}
自定义组件:
public MyViewModel VM { get; private set; }
public CustomComponent()
{
InitializeComponent();
VM = new MyViewModel();
}
在xaml中的用法:
<Label Text="{Binding VM.TestString, Source={x:Reference theComponent}}" />