本文介绍了为什么TargetNullValue更新为可空的源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应该是更新绑定 Target 当绑定评估为 null

除此之外,它似乎也设置 null (如果可能的话),当 Target 的值等于给出 TargetNullValue 。换句话说,它有效地设置了 null TargetNullValue 属性值之间的等价关系。但是这个文档根本没有提到。

In addition to that it also appears to set the Source to null (if possible), when the value of Target is equals to given TargetNullValue. In other words, it effectively sets up an equivalency between null and the TargetNullValue property's value. However this is not mentioned in the documentation at all.

看到这个例子:

<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 仅用于使测试更容易,与所讨论的效果无关。

Note: UpdateSourcetrigger is only set to make testing easier and has nothing to do with the effect in question.

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

If you put a breakpoint in NullableInt's setter, you can see that it gets triggered (with value == null) when you change the TextBox content to ''.

这是一个没有记录的行为, TargetNullValue 还是有其他副作用?

Is this a undocumented behavior by TargetNullValue or is there some other side effect in play here?

编辑:
我偶然发现这个话题,因为我正在看这个问题:

推荐答案

似乎是没有记录的行为。如果您查看当检索要使用的值时,实际上会检查该值是否等于TargetNullValue,如果是,则使用 null 替代:

It seems to be undocumented behavior. If you look at BindingExpressionBase.GetRawProposedValue() when retreiving the value to use, it actually checks to see if the value is equal to the TargetNullValue and if so, uses null instead:

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 将重置属性为零。

Indeed, if you set your TargetNullValue to be 5 instead of an empty string, you'll see that typing 5 will reset the property to null.

这篇关于为什么TargetNullValue更新为可空的源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 09:09