在 WPF 绑定中为 IValueConverter 实现获取 ConvertBack() 方法中的 Source 值 [英] Get the Source value in ConvertBack() method for IValueConverter implementation in WPF binding

查看:28
本文介绍了在 WPF 绑定中为 IValueConverter 实现获取 ConvertBack() 方法中的 Source 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将依赖属性绑定到 WPF 中的 textboxex.该属性是一个字符串,其中一些值由 '/' 分隔(例如: "1/2/3/4" ).我需要将单个值绑定到单独的文本框,这对 Convert() 方法的以下实现很好:

I am binding a dependency property to textboxex in WPF. The property is a string that has some values separated by '/' (example: "1/2/3/4" ). I need to bind individual values to separate textboxes which is fine with following implementation of Convert() method:

public object Convert(object value, Type targetType, object parameter,System.Globalization.CultureInfo culture)
{
  if (!string.IsNullOrEmpty(value as string))
  {
    String[] data = (value as string).Split('/');
    return data[Int16.Parse(parameter as string)];
  }
  return String.Empty;
}

我在 xaml 中使用 ConverterParameter 来指定所需值的位置.但是,问题在于 ConvertBack() 方法.我不知道如何获取源值,这样我就可以只在字符串中添加或更改一个值(在指定位置).

And I am using the ConverterParameter in xaml to specify the position of wanted value. However, the problem is with ConvertBack() method. I do not know, how to get the source value so I could just add or change just one value in the string (on the specified position).

感谢您的帮助.

推荐答案

在大多数情况下,您可以安全地使 ConvertBack 只抛出 NotImplementedException.

In most cases, you can safely make ConvertBack just throw NotImplementedException.

确实,您只是没有足够的信息来从其部分重新创建源值!

Indeed, you just haven't got enough information to recreate the source value from its part!

如果你真的需要反向转换(例如,如果你使用双向绑定),我会在视图模型(DataContext 中使用的类)中将属性拆分为 3 个字符串,并且分别绑定到它们.

If you really need the back conversion (e.g., if you use two-direction binding), I would split the property into 3 strings in the view model (the class used in DataContext), and bind to them separately.

这篇关于在 WPF 绑定中为 IValueConverter 实现获取 ConvertBack() 方法中的 Source 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆