有一个非常奇怪的问题令我感到困惑.就像下面的代码一样,我创建了一个[Button]并将其[Canvas.LeftProperty]多重绑定到[Entity.X]和[Entity.Z].[实体] ]类已实现[INotifyPropertyChaned].
它在Convert()方法中运行良好,[Entity.X]和[Entity.Z]正确传递给[Canvas.LeftProperty].
但问题是:当我用Canvas.SetLeft()方法更改[Button]的位置时,转换了ConvertBack()方法,但是没有将正确的值传递给[Entity],[in]中的[value] Entity.X]的设置部分似乎始终是旧部分.
PS:我发现了一个类似的问题,但它也没有解决.. :(
类似的问题:http://social.msdn.microsoft.com/Forums/zh-CN/wpf/thread/88B1134B-1DAA-4A54-94ED-BD724724D1EF
<Canvas>
<Button x:Name="btnTest">
<Canvas>
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
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
}
}
Run Code Online (Sandbox Code Playgroud)
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));
}
}
Run Code Online (Sandbox Code Playgroud)
您需要在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);
}
Run Code Online (Sandbox Code Playgroud)