更新
您可能已经在 Vlad 的帮助下解决了您的问题,我只是想我应该添加另一种在转换器中实际获取源值的方法。
首先你可以让你的转换器派生自DependencyObject,这样你就可以向它添加一个我们将绑定到的依赖属性
public class MyConverter : DependencyObject, IValueConverter
{
public static DependencyProperty SourceValueProperty =
DependencyProperty.Register("SourceValue",
typeof(string),
typeof(MyConverter));
public string SourceValue
{
get { return (string)GetValue(SourceValueProperty); }
set { SetValue(SourceValueProperty, value); }
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
//...
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
object targetValue = value;
object sourceValue = SourceValue;
//...
}
}
不幸的是,转换器没有DataContext,因此绑定无法开箱即用,但您可以使用 Josh Smith 的出色DataContextSpy:Artificial Inheritance Contexts in WPF
<TextBox>
<TextBox.Resources>
<src:DataContextSpy x:Key="dataContextSpy" />
</TextBox.Resources>
<TextBox.Text>
<Binding Path="YourProperty"
ConverterParameter="1">
<Binding.Converter>
<src:MyConverter SourceValue="{Binding Source={StaticResource dataContextSpy},
Path=DataContext.YourProperty}"/>
</Binding.Converter>
</Binding>
</TextBox.Text>
</TextBox>
更新结束
Dr.WPF 对此有一个优雅的解决方案,请参阅以下线程
The way to access binding source in ConvertBack()?
编辑
使用 Dr.WPF 的解决方案,您可以通过这个(可能有点冗长)示例代码向转换器提供字符串索引和源 TextBox
<TextBox dw:ObjectReference.Declaration="{dw:ObjectReference textBoxSource}">
<TextBox.Text>
<Binding Path="YourStringProperty"
Converter="{StaticResource YourConverter}">
<Binding.ConverterParameter>
<x:Array Type="sys:Object">
<sys:Int16>1</sys:Int16>
<dw:ObjectReference Key="textBoxSource"/>
</x:Array>
</Binding.ConverterParameter>
</Binding>
</TextBox.Text>
</TextBox>
然后您可以稍后在 ConvertBack 方法中访问索引和 TextBox
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
object[] parameters = parameter as object[];
short index = (short)parameters[0];
object source = (parameters[1] as TextBox).DataContext;
//...
}