文本中的条件 属性

Conditional in Text property

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

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

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

您可以使用 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>

这是示例转换器class

 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>