WPFConverter(值转换器)使用例子

来源:互联网 发布:淘宝天龙助手脚本没了 编辑:程序博客网 时间:2024/06/11 05:00

1.创建一个类,必须继承IValueConverter接口,在命名空间System.Windows.Data下

public class TimeSpanToStringConverter : IValueConverter
{
/// <summary>
/// 由TimeSpan值转换为字符串,用于时间显示
/// </summary>
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
TimeSpan timespan = (TimeSpan)value;
return (timespan.Hours > 0 ? timespan.Hours.ToString() + ":" : "") + (timespan.Minutes < 10 ? "0" : "") + timespan.Minutes + ":" + (timespan.Seconds < 10 ? "0" : "") + timespan.Seconds;
}


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


    }


2.在资源文件xaml里加入 转换器,converters为命名空间定义 比如xmlns:converters="clr-namespace:Converters"

 <converters:TimeSpanToStringConverter  x:Key="dateConverter"/>,或者直接在页面中添加  

  <Window.Resources>
        <local:TimeSpanToStringConverter x:Key="dateConverter"/>
    </Window.Resources>


3.使用转换器

<Button Content="{Binding Path=isDownloading, Converter={StaticResource dateConverter}}" > </Button>

0 0
原创粉丝点击