There is a very strange problem which is confusing me a lot.Just like the code below,I had created a [Button] and multibound its [Canvas.LeftProperty] to [Entity.X] and [Entity.Z].The [Entity] class has implemented the [INotifyPropertyChaned].
It works well in Convert() Method, [Entity.X] and [Entity.Z] are correctly passed to the [Canvas.LeftProperty].
But the problem is:when I changed the [Button]'s location with Canvas.SetLeft() method,the ConvertBack() methods was fired,but the correct value was not passed to the [Entity],the [value] in [Entity.X]'s set section seemed to be the old one all the time.
PS:I found a similar question ,but it was not solved either.. :(
Similiar question:http://social.msdn.microsoft.com/Forums/zh-CN/wpf/thread/88B1134B-1DAA-4A54-94ED-BD724724D1EF
<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));
}
}
You need to specify the Binding mode on each Binding within your MultiBinding that you want to use in your ConvertBack method. So for the code you posted above the following change to your 'Binding code' should fix your issue:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With