我正在使用 .NET 8 MAUI 中的组件进行一些测试。我正在测试一个名为
NewContent1
的基本组件。这是页面的XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyComponent.NewContent1">
<Entry Text="{Binding MyProperty, Mode=TwoWay}" />
</ContentView>
然后这是背后的代码:
namespace MyComponent;
public partial class NewContent1 : ContentView
{
public NewContent1()
{
InitializeComponent();
BindingContext = this;
}
public static readonly BindableProperty MyPropertyProperty = BindableProperty.Create(
nameof(MyProperty),
typeof(string),
typeof(NewContent1),
string.Empty);
public string MyProperty
{
get => (string)GetValue(MyPropertyProperty);
set => SetValue(MyPropertyProperty, value);
}
}
简单。现在,在
MainPage
中,我添加组件,这就是 XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
x:Class="MyComponent.MainPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:component="clr-namespace:MyComponent;assembly=MyComponent">
<ScrollView>
<VerticalStackLayout Padding="30,0" Spacing="25">
<component:NewContent1 MyProperty="{Binding MyVariable}" />
<Label Text="{Binding MyVariable}" />
</VerticalStackLayout>
</ScrollView>
</ContentPage>
然后这是背后的代码
public partial class MainPage : ContentPage
{
private string _myVariable;
public string MyVariable
{
get => _myVariable;
set
{
_myVariable = value;
OnPropertyChanged(nameof(MyVariable));
}
}
public MainPage()
{
InitializeComponent();
BindingContext = this;
}
}
因此,我希望当用户在
Entry
中键入任何内容时,属性 MyProperty
会更新(并且这是有效的),而且 MyVariable
中的变量 MainPage
也会更新,但这不起作用。
我错过了什么?
从BindableProperty来看,
defaultBindingMode
是BindingMode.OneWay
,也就是说MyProperty
的改变不会带来MyVariable
的改变。
另一个问题,当您在页面的构造函数中设置 BindingContext 时,
BindingContext
的 ContentPage
本身就是。 NewContent1
应该从其父级(页面)继承 BindingContext。但是你还在ContentView的构造函数中设置了BindingContext = this;
,这导致MyProperty
无法绑定到MyVariable
。
对于
BindableProperty
,在 Create
方法中显式设置 BindingMode,
public static readonly BindableProperty MyPropertyProperty = BindableProperty.Create(
nameof(MyProperty),
typeof(string),
typeof(NewContent1),
string.Empty,
BindingMode.TwoWay);
并且当您设置
NewContent1
的BindingContext时,在Content.BindingContext = this;
构造函数中设置BindingContext = this;
而不是NewContent1
,
public NewContent1()
{
InitializeComponent();
Content.BindingContext = this;
}
或者您也可以根据需要使用 x:reference 表达式,例如
<Entry Text="{Binding MyProperty, Source={x:Reference this}}" />
那么就不需要在
NewContent1
构造函数中设置BindingContext了,
public NewContent1()
{
InitializeComponent();
//Content.BindingContext = this; //remove
}
希望有帮助!