Multibinding ConvertBack没有将正确的值传递给source?

时间:2013-05-29 04:30:33

标签: wpf multibinding

有一个非常奇怪的问题令我感到困惑。就像下面的代码一样,我创建了一个[Button]并将其[Canvas.LeftProperty]多重绑定到[Entity.X]和[Entity.Z]。 [Entity]类已实现[INotifyPropertyChaned]。

它在Convert()方法中运行良好,[Entity.X]和[Entity.Z]正确传递给[Canvas.LeftProperty]。

但问题是:当我用Canvas.SetLeft()方法更改[Button]的位置时,转换了ConvertBack()方法,但是没有将正确的值传递给[Entity],[value ] [Entity.X]的set部分似乎一直都是旧的。

PS:我发现了一个类似的问题,但它也没有解决.. :(

类似问题:http://social.msdn.microsoft.com/Forums/zh-CN/wpf/thread/88B1134B-1DAA-4A54-94ED-BD724724D1EF

XAML:

<Canvas>
  <Button x:Name="btnTest">
<Canvas>

BindingCode:

private void Binding()
{
 var enity=DataContext as Entity;
 var multiBinding=new MutiBinding();
 multiBinding.Mode=BindingMode.TwoWay;
 multiBinding.Converter=new LocationConverter();
 multiBinding.Bindings.Add(new Binding("X"));
 multiBinding.Bindings.Add(new Binding("Z"));
 btnTest.SetBinding(Canvas.LeftProperty,multiBinding);
}

转换器:

public class LocationConverter: IMultiValueConverter
{
  public object Convert(object[] values, TypetargetType,object parameter, CultureInfo culture)
  {
    return (double)values[0]*(double)values[1];
  }

  public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
  {
    return new object[]{ (double)value,Binding.DoNoting};//!!value here is correct
  }
}

实体:

public class Entity:INotifyPropertyChanged
{
  private double x=0d;
  private double z=0d;

  public double X
  {
    get{ return x;}
    set{ 
         x=value;//!!value here is not correctly passed
         CallPropertyChanged("X");}
       } 

  public double Z
  {
    get{ return z;}
    set{ 
         z=value;//!!value here is not correctly passed
         CallPropertyChanged("Z");}
       } 
  } 

  public event PropertyChangedEventHandler PropertyChanged;

  private void CallPropertyChanged(String info)
  {
     if(PropertyChanged!=null)
        PropertyChanged(this,new PropertyChangedEventArgs(info));
  }
}

1 个答案:

答案 0 :(得分:9)

您需要在MultiBinding中的每个Binding上指定要在ConvertBack方法中使用的Binding模式。因此,对于您在上面发布的代码,您对“绑定代码”进行了以下更改。应该解决你的问题:

private void Binding()
{
 var enity=DataContext as Entity;
 var multiBinding=new MutiBinding();
 multiBinding.Mode=BindingMode.TwoWay;
 multiBinding.Converter=new LocationConverter();
 multiBinding.Bindings.Add(new Binding("X"){Mode = BindingMode.TwoWay});
 multiBinding.Bindings.Add(new Binding("Z"));
 btnTest.SetBinding(Canvas.LeftProperty,multiBinding);
}