为什么TargetNullValue更新可为空来源

时间:2016-04-04 12:11:46

标签: c# wpf data-binding nullable

当绑定Target评估为Source时,

TargetNullValue应该更新绑定null

  

获取或设置当源的值为null时在目标中使用的值。

除此之外,当Source的值等于给定null时,它似乎也会将Target设置为TargetNullValue(如果可能)。换句话说,它有效地设置了nullTargetNullValue属性值之间的等效性。但是,文档中根本没有提到这一点。

见这个例子:

<Window x:Class="WPF_Sandbox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF_Sandbox"
        Title="MainWindow"
        x:Name="ThisControl">
    <StackPanel x:Name="MainStackPanel">
        <TextBox x:Name="MyTextBox" Text="{Binding NullableInt, ElementName=ThisControl, TargetNullValue='', UpdateSourceTrigger=PropertyChanged}" />
    </StackPanel>
</Window>


public partial class MainWindow : Window
{
    private int? nullableInt;

    public int? NullableInt
    {
        get { return nullableInt; }
        set { nullableInt = value; }
    }

    public MainWindow()
    {
        InitializeComponent();
    }
}

注意:UpdateSourcetrigger仅用于简化测试,与相关效果无关。

如果您在NullableInt的设置器中放置断点,当您将value == null内容更改为{{1}时,您可以看到它被触发(使用TextBox) }}

这是''的无证行为还是在这里有其他副作用?

编辑: 我偶然发现了这个话题,因为我在看这个问题:
Set value to null in WPF binding

1 个答案:

答案 0 :(得分:9)

似乎是无证行为。如果在检索要使用的值时查看BindingExpressionBase.GetRawProposedValue(),它实际上会检查该值是否等于TargetNullValue,如果是,则使用null代替:

internal virtual object GetRawProposedValue()
{
    object value = Value;

    // TargetNullValue is the UI representation of a "null" value.  Use null internally.
    if (Object.Equals(value, EffectiveTargetNullValue))
    {
        value = null;
    }

    return value;
}

EffectiveTargetNullValue最终是TargetNullValue)。

事实上,如果您将TargetNullValue设置为5而不是空字符串,则您会看到键入5会将该属性重置为null。