我在 ViewModel 中获得了一个列表,并且 UI 对属性值的更改没有反应。 这是关于按钮(SfChip)背景颜色的,未更新。 (选定的按钮为红色,所有其他按钮为白色)。
这是 XAML:
<syncfusion:SfChipGroup ItemsSource="{Binding PageButtonList}" >
<syncfusion:SfChipGroup.ItemTemplate>
<DataTemplate x:DataType="models:PageModel">
<syncfusion:SfChip Text="{Binding Title}"
Background="{Binding IsCurrentPage, Converter={StaticResource BoolToColorConverter}}"
TextColor="Black" />
</DataTemplate>
</syncfusion:SfChipGroup.ItemTemplate>
</syncfusion:SfChipGroup>
背景颜色使用
bool
绑定到 BoolToColorConverter
:
<toolkit:BoolToObjectConverter x:Key="BoolToColorConverter"
TrueObject="{x:Static Colors.Red}"
FalseObject="{x:Static Colors.White}"/>
IsCurrentPage
的布尔值最初为true,因此颜色为红色。每次我向 PageButtonList 添加 PageModel 元素时,我都会将所有 IsCurrentPage
属性设置为 false
,只有最后一个是 true
。
private void UpdatePageButtonList()
{
foreach (var pageModel in PageButtonList)
{
pageModel.IsCurrentPage = pageModel.Id == CurrentPageNumber;
}
}
即使逐渐添加列表条目并显示更多 SfChip,它们仍然保持红色。我可以在方法
UpdatePageButtonList()
中设置断点,并看到第一个列表条目的 IsCurrentPage
设置为 false
。
可能 UI 无法识别属性的更改或转换器无法工作。
为什么SfChip的背景色没有变成白色?
public class PageModel
{
public int Id { get; set; }
public string Title => (Id + 1).ToString();
public bool IsCurrentPage { get; set; }
public PageModel(int id)
{
Id = id;
IsCurrentPage = true;
}
}
问题是您的
IsCurrentPage
属性不会调用 PropertyChanged
事件,因此 UI 不会收到有关更改的通知。
在MAUI中,所有可以改变其值的属性以及在值更新时需要更新UI的绑定表达式中使用的属性都需要是可观察的。这同样适用于 ViewModel 和 Model。
当您在 ViewModel 中使用 Model 类时,例如在
List<PageModel>
或 ObservableCollection<PageModel>
中,并且您绑定到所述 PageModel
的属性,例如IsCurrentPage
,那么这个性质一定是可观察的。
确保您的
PageModel
类实现 INotifyPropertyChanged 接口,可以手动执行或使用 MVVM 社区工具包中的源生成器:
public class PageModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public int Id { get; set; }
public string Title => (Id + 1).ToString();
private bool _isCurrentPage;
public bool IsCurrentPage
{
get => _isCurrentPage;
set
{
if(value == _isCurrentPage) return;
_isCurrentPage = value;
OnPropertyChanged();
}
}
public PageModel(int id)
{
Id = id;
IsCurrentPage = true;
}
}
public partial class PageModel : ObservableObject
{
public int Id { get; set; }
public string Title => (Id + 1).ToString();
[ObservableProperty]
private bool _isCurrentPage; //becomes IsCurrentPage public property
public PageModel(int id)
{
Id = id;
IsCurrentPage = true;
}
}