如何获得对称的TwoWay绑定?

时间:2012-03-23 15:22:56

标签: wpf xaml

在调试WPF应用程序中的问题时,我注意到TwoWay数据绑定似乎不对称。这是一个例子:

<Window x:Class="ConverterTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:local="clr-namespace:ConverterTest"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:TextConverter x:Key="textConverter"/>
    </Window.Resources>
    <Grid>
        <TextBox x:Name="txt1" Height="24" Margin="0" VerticalAlignment="Top"/>
        <TextBox x:Name="txt2" Height="24" Margin="0,40,0,0"  VerticalAlignment="Top"
                 Text="{Binding ElementName=txt1, Path=Text, 
                        Mode=TwoWay,
                        UpdateSourceTrigger=PropertyChanged, 
                        Converter={StaticResource textConverter}}"/>
    </Grid>
</Window>

转换器如下所示:

public class TextConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, System.Type targetType,
         object parameter, System.Globalization.CultureInfo culture)
    {
        return value.ToString().ToUpper();
    }

    public object ConvertBack(object value, System.Type targetType, 
         object parameter, System.Globalization.CultureInfo culture)
    {
        return value.ToString().ToLower();
    }

    #endregion
}

txt1内修改时,只调用Convert();但在txt2内进行编辑时,会先调用ConvertBack(),然后调用Convert()

换句话说,TwoWay绑定似乎是这样的:

  • 更新源属性后,将更新目标属性。
  • 更新目标属性后,首先更新源属性,然后再次更新目标属性。

MSDN documentation只是说:

  

导致对source属性或target属性的更改自动更新另一个属性。

从那句话来看,我原本期望以下行为:

  • 更新源属性后,将更新目标属性。
  • 更新目标属性后,将更新源属性。

有没有办法实现这种对称行为(纯粹在XAML中,没有C#编程)?

编辑:我刚刚发现在WPF 3.5中,TwoWay绑定是对称的。但是,在WPF 4.0中,行为已更改(如上所述)。

1 个答案:

答案 0 :(得分:2)

嗯,完全对称无法实现,因为:

  • 更新源时,控件只需显示新值period。没有任何幻想发生。
  • 当目标被更新时,在将其写入源之前,可以在荒谬的地方取消值的更改。

例如:验证。

当源代码更新时,例如,从代码中,它通过了所有验证(除非您忘记检查,但这是另一个问题)。控件只显示新值。

当目标更新时,首先将值转换回转换器中以进行操作,然后强制,验证,然后最后设置源。

但如您所见,该值可能已在目标和源之间进行了修改,因此该值会再次转换,最后显示。

奖励:要了解值可以更改的位置和顺序,请参阅Dependency Property Value Precedence