Update
您可能已经在以下人员的帮助下解决了您的问题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
: 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对此有一个优雅的解决方案,请参阅以下线程
如何在ConvertBack()中访问绑定源?
Edit
使用 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>
然后您可以稍后访问索引和TextBox
在ConvertBack方法中
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;
//...
}