概述:我有两个属性:
IsPast
IsCurrentMonth
如果是过去的月份或不是当前月份,我希望以红色显示标签。
下面的代码是默认Maui应用程序的收缩版本。如果你运行它,你会得到红色标签(预期的)。在一次点击后,它保持红色(预期的),但随后的点击会切换红色的开关。这是一个bug还是我不明白DataTrigger/Style/whatever的工作方式:
查看型号:
public class ViewModel : INotifyPropertyChanged
{
private bool _isPast;
public bool IsPast
{
get => _isPast;
set
{
_isPast = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsPast)));
}
}
private bool _isCurrentMonth;
public bool IsCurrentMonth
{
get => _isCurrentMonth;
set
{
_isCurrentMonth = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsCurrentMonth)));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
然后XAML:
<?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:local="clr-namespace:BugMaui"
x:Class="BugMaui.MainPage"
x:DataType="local:ViewModel">
<VerticalStackLayout>
<HorizontalStackLayout>
<Label Text="IsPast: " />
<Label Text="{Binding IsPast}" />
</HorizontalStackLayout>
<HorizontalStackLayout>
<Label Text="IsCurrentMonth: " />
<Label Text="{Binding IsCurrentMonth}" />
</HorizontalStackLayout>
<Label
Text="Hello, World!"
FontSize="32"
HorizontalOptions="Center">
<Label.Style>
<Style TargetType="Label">
<Style.Triggers>
<DataTrigger TargetType="Label" Binding="{Binding IsPast}" Value="True">
<Setter Property="Background" Value="Red" />
</DataTrigger>
<DataTrigger TargetType="Label" Binding="{Binding IsCurrentMonth}" Value="False">
<Setter Property="Background" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</Label.Style>
</Label>
<Button
Text="Click me"
Clicked="OnCounterClicked"/>
</VerticalStackLayout>
</ContentPage>
而背后的代码:
public partial class MainPage : ContentPage
{
ViewModel viewModel;
public MainPage()
{
InitializeComponent();
viewModel = new ViewModel { IsCurrentMonth = true, IsPast = true };
BindingContext = viewModel;
}
private void OnCounterClicked(object sender, EventArgs e)
{
viewModel.IsPast = !viewModel.IsPast;
viewModel.IsCurrentMonth = !viewModel.IsCurrentMonth;
}
}
1条答案
按热度按时间klr1opcd1#
您可以使用
MultiTrigger
更好地表达条件(IsPast is true && IsCurrentMonth is false
),如下所示:有关详细信息,请查看. NET MAUI MultiTrigger文档。