好的,我正在学习 .NET Maui。我一直在学习导航和页面布局,我想我已经掌握了窍门。然后我开始数据绑定并停止了。从我读过的所有内容来看,我所拥有的应该有效,但事实并非如此。
我有一个简单的测试页,上面有两个标签。这两个标签(据说)绑定到类的特定属性,并且应该显示标签中的值。它不是。事实上,什么也没有显示,什么也没有。
好的,我有一个包含以下 xaml 的测试页。
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyNamespace.Pages.TestPage"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
Title="TestPage">
<Grid Margin="15,15,15,15">
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid Grid.Row="1" Grid.Column="0" Margin="25,0,25,25" RowSpacing="20" ColumnSpacing="20">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" TextColor="White" FontSize="24" FontAttributes="Bold" x:Name="lblOne" BindingContext="{Binding DisplayName, Mode=TwoWay}"></Label>
<Label Grid.Row="1" Grid.Column="0" TextColor="White" FontSize="24" FontAttributes="Bold" x:Name="lblTwo" BindingContext="{Binding SoundFX, Mode=TwoWay}"></Label>
</Grid>
</Grid>
</ContentPage
请忽略嵌套的网格,因为页面最终会容纳更多网格。目前,它只有两个标签,据说绑定到 DisplayName 和 SoundFX,这两个标签都是我的类的字符串属性。保存值的类如下所示:
public class MyItem
{
public String DisplayName { get; set; }
public String SoundFX { get; set; }
public MyItem(String name, String fxresource)
{
DisplayName = name;
SoundFX = fxresource;
}
}
测试页的 C# 是:
public partial class TestPage : ContentPage
{
private MyItem _item;
public TestPage()
{
InitializeComponent();
_item = new MyItem("Name to Display", "SoundFX Value");
this.BindingContext = _item;
}
}
除非我错过了某些东西(这是完全可能的情况,因为我正在自己学习这一点),否则相关标签应该显示适当的文本值,但实际上它们什么也不显示。该页面完全空白。
如果我更改构造函数以消除绑定并简单地设置 labels.Text,它可以正常工作并且标签显示正确,所以我认为布局不是问题。它必须是带有绑定的东西。
public TestPage()
{
InitializeComponent();
//_item = new MyItem("Name to Display", "SoundFX Value");
//this.BindingContext = _item;
lblOne.Text = "Name to Display";
lblTwo.Text = "SoundFX Value";
}
我不确定我在这个数据绑定上做错了什么,我希望能指出正确的方向。
它在一种情况下起作用而在另一种情况下不起作用的原因与通知您的属性更改有关,它是一个 MVVM 概念,它使用
INotifyPropertyChanged
接口来通知您的属性发生的更改,然后将这些更改显示到你的观点。
现在您可以自己编写样板文件
实现 INotifyPropertyChanged - 是否存在更好的方法?
或者你可以做我现在喜欢做的事情,就是使用