有条件的Text属性

时间:2016-01-06 21:13:48

标签: xaml windows-phone-8.1

我有以下XAML,它显示一个滑块元素的值,后面是秒:

<Run Text="{Binding ElementName=TimeToGetReadySlider,Path=Value}"/>
<Run Text=" seconds"/>

TimeToGetReadySlider的值为1时,我希望第二个元素为“秒”。如何实现?

1 个答案:

答案 0 :(得分:1)

您可以使用Converter执行此操作。试试这个实现

   <StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <Slider x:Name="TimeToGetReadySlider" Maximum="10" SmallChange="1"></Slider>

        <TextBlock Text="{Binding ElementName=TimeToGetReadySlider,Path=Value,Converter={StaticResource MyConverter}}"></TextBlock>
   </StackPanel>

以下是示例转换器类

 public class ConverterClass : IValueConverter
    {      
     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
        var val = (double)value;

        if (val < 2)
        {
            return val + " second";
        }
        return val + "seconds";
      }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
        throw new NotImplementedException();
      }
   }

在您的网页上注册

 <phone:PhoneApplicationPage.Resources>
        <test:ConverterClass x:Name="MyConverter"/>
 </phone:PhoneApplicationPage.Resources>