是否可以从页面XAML文件设置NameLabel.Text值 直接地?没有定义样板可绑定属性?
如果您经常重复使用布局,自定义
Contenview
是一个很好的方法。
由于我们无法通过 Contenview
属性直接引用 x:Name
内部的控件,因此我们需要为其添加必要的 BindableProperty
。
这是一个定制的
Contenview
,你可以参考它的代码。
MyItemView.xaml.cs
public partial class MyItemView : ContentView
{
public MyItemView()
{
InitializeComponent();
}
public String YourName
{
get
{
String value = (String)GetValue(YourNameProperty);
return value;
}
set
{
SetValue(YourNameProperty, value);
}
}
public static readonly BindableProperty YourNameProperty = BindableProperty.Create(nameof(YourName)
, typeof(String)
, typeof(MyItemView), defaultBindingMode: BindingMode.TwoWay, propertyChanged: OnYourNameChanged);
static void OnYourNameChanged(BindableObject bindable, object oldValue, object newValue)
{
Console.WriteLine("-----------------> " + newValue);
}
}
MyItemView.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="MauiApp1124.Views.MyItemView"
x:Name="myItemView"
>
<VerticalStackLayout>
<Grid>
<Label Text="{Binding Source={x:Reference myItemView}, Path=YourName}" />
</Grid>
</VerticalStackLayout>
</ContentView>
这是使用示例:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:views="clr-namespace:MauiApp1124.Views"
x:Class="MauiApp1124.MainPage">
<VerticalStackLayout
Spacing="25"
Padding="30,0"
VerticalOptions="Center">
<views:MyItemView YourName="welcome"></views:MyItemView>
<views:MyItemView YourName="Hi"></views:MyItemView>
</VerticalStackLayout>
</ContentPage>
更多信息请查看官方文档:ContentView。