为普通内容页编译绑定

后端开发 2026-07-10

是否有方法在没有视图模型时,在普通内容页中对绑定进行编译?

我有一个带有可绑定属性 "backgroundcolor" 的内容页,且在设置按钮背景颜色方面,它工作得很好

public partial class EditPage : ContentPage
{
    //Background color
    private readonly BindableProperty bBackgroundcolor = BindableProperty.Create(nameof(backgroundcolor), typeof(Color), typeof(EditPage));

    public Color backgroundcolor
    {
        get => (Color)GetValue(bBackgroundcolor);
        set => SetValue(bBackgroundcolor, value);
    }



    public EditPage(SleepDateWithBoolean CurrentSleepDateEditPopup)
    {
        InitializeComponent();
        BindingContext = this;
        ...
    }

}

我有XAML代码:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="SleepDiary.EditPage"
             Title="EditPage">
    <VerticalStackLayout>                    
        <Button
                x:Name="SaveAndCloseButton"
                Text="Save and close"
                BackgroundColor="{Binding backgroundcolor}"
                Clicked="SaveAndClose"/>
    </VerticalStackLayout>
</ContentPage>

编译时会出现以下警告:

"如果指定了x:DataType,绑定可以被编译以提升运行时性能。有关更多信息,请参阅 https://learn.microsoft.com/dotnet/maui/fundamentals/data-binding/compiled-bindings。"

在没有视图模型时,是否有在普通内容页中对绑定进行编译的方法?

我知道应该使用 "x:DataType",但我不知道该写什么?

        <Button
                x:Name="SaveAndCloseButton"
                Text="Save and close"
                BackgroundColor="{Binding backgroundcolor, x:DataType=???}"
                Clicked="SaveAndClose"/>

先行感谢!

解决方案

可绑定属性有一个 命名约定 ,你没有遵循

Anyway对于你的情况,实际上你并不需要BindableProperty,你只需要一个普通的属性

Color backgroundColor;
public Color BackgroundColor
{
   get => backgroundColor;
   set
   {
      if (backgroundColor == value) 
      return;
      backgroundColor = value;
      OnPropertyChanged(nameof(BackgroundColor));
   }
}

编辑:

将以下内容添加到你的XAML以修复已编译的绑定警告:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="SleepDiary.EditPage"
             xmlns:sd="clr-namespace:SleepDiary"
             x:Name="this"
             Title="EditPage">
    <VerticalStackLayout>                    
        <Button
                x:Name="SaveAndCloseButton"
                Text="Save and close"
                BackgroundColor="{Binding BackgroundColor, Source={x:Reference this}, x:DataType=sd:EditPage}"
                Clicked="SaveAndClose"/>
    </VerticalStackLayout>
</ContentPage>
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章