我想显示视频的播放时间。我有一个标签,格式说明符如下:
<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();
}
}
...
}
在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}" />
答案 0 :(得分:4)
Xaml似乎被两种不同类型的文本绑定所迷惑 - 一种来自触发器而另一种是“直接”这就是它的工作原理:
<Label VerticalOptions="Center" HorizontalOptions="StartAndExpand">
<Label.Triggers>
<DataTrigger TargetType="Label" Binding="{Binding IsPlaying}" Value="True">
<Setter Property="Text" Value="{Binding CurrentTime, StringFormat='{0:D3} seconds'}" />
</DataTrigger>
<DataTrigger TargetType="Label" Binding="{Binding IsPlaying}" Value="False">
<Setter Property="Text" Value="Not playing" />
</DataTrigger>
</Label.Triggers>
</Label>
考虑选项为标签赋予“默认”值,并将其作为没有样式的孩子进行
<Label VerticalOptions="Center" HorizontalOptions="StartAndExpand" Text="Not playing">
<Label.Triggers>
<DataTrigger TargetType="Label" Binding="{Binding IsPlaying}" Value="True">
<Setter Property="Text" Value="{Binding CurrentTime, StringFormat='{0:D3} seconds'}" />
</DataTrigger>
</Label.Triggers>
</Label>