wpf数据绑定失败

来源:互联网 发布:网络经营许可证申请 编辑:程序博客网 时间:2024/05/21 08:37

原因:目标数据类型与绑定源数据类型不一致

解决:自己实现IValueConverter,在convert()和ConvertBack (),编写转换代码

 

示例:

[ValueConversion(typeof(DateTime), typeof(String))]

public class DateConverter : IValueConverter{

 public object Convert(object value, Type targetType,object parameter, CultureInfo culture) {

DateTime date = (DateTime)value;

 return date.ToShortDateString();

}

public object ConvertBack(object value, Type targetType,object parameter, CultureInfo culture) {

string strValue = value as string; DateTime resultDateTime;

if (DateTime.TryParse(strValue, out resultDateTime)) {

 return resultDateTime;

 }

return DependencyProperty.UnsetValue;

}

}

 

废话:在xaml里编写绑定,编译器会自己转换,自己在后台代码绑定则需转换

原创粉丝点击