验证之 IValueConverter 简单 Demo

实现简单的年龄划分:

  如果年龄小于18则显示:年龄:x,未成年人;

      否则:年龄:x,成年人;

 

代码:

[ValueConversion(typeof(int), typeof(String))]
public class AgeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        int age = System.Convert.ToInt32(value);

        if (age < 18)
        {
            return $"年龄:{age},未成年人";
        }

        return $"年龄:{age},成年人";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

 

窗口代码:

<StackPanel>
    <Slider x:Name="age" Minimum="0" Maximum="100" />
    <Label >
        <Label.Content>
            <Binding  ElementName="age" Path="Value" Mode="OneWay" UpdateSourceTrigger="PropertyChanged">
                <Binding.Converter>
                    <local:AgeConverter/>
                </Binding.Converter>
            </Binding>
        </Label.Content>
    </Label>
</StackPanel>

 

posted @ 2021-02-08 11:53  蜜铀  阅读(73)  评论(0编辑  收藏  举报