【发布时间】:2018-01-05 13:07:51
【问题描述】:
我想在视频中显示经过的时间。我有一个带有格式说明符的标签,如下所示:
<Label Text="{Binding CurrentTime, StringFormat='{0:D3} seconds'}" />
这行得通,我得到一个像053 seconds 这样的字符串。我想在视频未播放时显示文本Not playing,我这样指定:
<Label Text="{Binding CurrentTime, StringFormat='{0:D3} seconds'}">
<Label.Triggers>
<DataTrigger TargetType="Label" Binding="{Binding IsPlaying}" Value="False">
<Setter Property="Text" Value="Not playing" />
</DataTrigger>
</Label.Triggers>
</Label>
当视频没有播放时,这会正确显示Not playing,但是当它播放时,标签会永远停留在000 seconds。出了什么问题?
编辑
视图如下所示:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyNamespace.VideoPage"
x:Name="ThePage"
BindingContext="{x:Reference Name=ThePage}">
<StackLayout>
<Label VerticalOptions="Center" Text="{Binding CurrentTime, StringFormat='{0:D3} seconds'}" HorizontalOptions="StartAndExpand">
<Label.Triggers>
<DataTrigger TargetType="Label" Binding="{Binding IsPlaying}" Value="False">
<Setter Property="Text" Value="Not playing" />
</DataTrigger>
</Label.Triggers>
</Label>
<!-- More stuff -->
</StackLayout>
</ContentPage>
代码隐藏如下:
public partial class VideoPage : ContentPage
{
private int currentTime;
public int CurrentTime
{
get { return currentTime; }
set
{
currentTime = value;
OnPropertyChanged();
}
}
private bool isPlaying;
public bool IsPlaying
{
get { return isPlaying; }
set
{
isPlaying = value;
OnPropertyChanged();
}
}
...
}
编辑 2
在 Yuri 的回答的帮助下,我用以下方法修复了它
<ContentPage.Resources>
<ResourceDictionary>
<Style TargetType="Label" x:Key="PlayingStyle">
<Setter Property="Text" Value="Not playing" />
<Style.Triggers>
<DataTrigger TargetType="Label" Binding="{Binding IsPlaying}" Value="True">
<Setter Property="Text" Value="{Binding CurrentTime, StringFormat='{0:D3} seconds'}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
</ContentPage.Resources>
...
<Label Style="{StaticResource PlayingStyle}" />
【问题讨论】:
-
你绑定的类是否实现了 INotifyPropertyChanged?
-
@Jason 当我没有触发器时,值设置正确并更新。
-
你的模型或视图模型是什么样的?
-
@Ethan2Pants 我添加了相关部分
-
并非所有部分。我看不到“ThePage”是如何绑定的,并且 OnPropertyChanged 是如何被调用的,但是接口 INotifyPropertyChanged 是在哪里定义的?
标签: xaml xamarin data-binding xamarin.forms datatrigger