【问题标题】:Multibinding ConvertBack doesn't pass the correct value to source?多重绑定 ConvertBack 没有将正确的值传递给源?
【发布时间】:2013-05-24 05:15:55
【问题描述】:

有一个非常奇怪的问题让我很困惑。就像下面的代码一样,我创建了一个 [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>

绑定代码:

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));
  }
}

【问题讨论】:

  • 我可以看看你的整个财产吗?
  • @dennis schütz,感谢您抽出宝贵时间。上面的代码现已更新。

标签: wpf multibinding


【解决方案1】:

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

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);
}

【讨论】:

  • 非常感谢,它确实有效!但是为什么必须指定每个 Binding 上的 BindingMode,因为 MultiBinding 已经有一个?您能给我更多建议吗?谢谢!
猜你喜欢
  • 2010-10-19
  • 2011-06-28
  • 1970-01-01
  • 2023-01-31
  • 1970-01-01
  • 2018-05-10
  • 1970-01-01
  • 2021-04-21
  • 2019-10-20
相关资源
最近更新 更多