Sin*_*atr 2 c# wpf mvvm imultivalueconverter
我正在使用MultiBinding转换器将(x,y)坐标传递给方法。
我不能让它在反向工作:
public class MyConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var x = (int)values[0];
var y = (int)values[1];
return Model.Get(x, y);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
Model.Set(x, y, value); // how to get x, y here?
return new object[] { Binding.DoNothing, Binding.DoNothing };
}
}
Run Code Online (Sandbox Code Playgroud)
数据将以表格的形式可视化。这是单元格模板:
<TextBox>
<TextBox.Text>
<MultiBinding Converter="{StaticResource converter}" Mode="TwoWay">
<Binding Path="X" Mode="OneWay" />
<Binding Path="Y" Mode="OneWay" RelativeSource="..." />
</MultiBinding>
</TextBox.Text>
</TextBox>
Run Code Online (Sandbox Code Playgroud)
这个想法是使用转换器,它接收x(来自单元格视图模型)和y(来自父列视图模型, notice RelativeSource)并调用Get(x,y)以显示值。
但是,当用户输入某些内容时,会ConvertBack被调用并且我需要调用Set(x, y, value)方法。
我如何通过x和y进入ConvertBack?
可能会有或多或少的脏变通方法来使这种多值转换器工作。但我建议您保持多值转换器单向,但返回一个包装实际文本属性的容器对象。
不是直接绑定到TextBox.Text属性,而是绑定到其他一些属性(例如DataContext或Tag),然后将文本绑定到容器值。
小例子:
<TextBox Text="{Binding Value}">
<TextBox.DataContext>
<MultiBinding Converter="{StaticResource cMyConverter}">
<Binding Path="X"/>
<Binding Path="Y"/>
</MultiBinding>
</TextBox.DataContext>
</TextBox>
Run Code Online (Sandbox Code Playgroud)
带容器和转换器:
public class ValueProxy
{
public int X { get; set; }
public int Y { get; set; }
public string Value
{
get { return Model.Get(X, Y); }
set { Model.Set(X, Y, value); }
}
}
public class MyConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var x = (int)values[0];
var y = (int)values[1];
return new ValueProxy { X = x, Y = y };
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
return new object[] { Binding.DoNothing, Binding.DoNothing };
}
}
Run Code Online (Sandbox Code Playgroud)