c# - 为什么 TargetNullValue 更新可为空的 Source

标签 c# wpf data-binding nullable

TargetNullValue应该在绑定(bind) Source 评估为 null 时更新绑定(bind) Target:

Gets or sets the value that is used in the target when the value of the source is 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 的 setter 中放置一个断点,您可以看到它在您更改 TextBox 时被触发(使用 value == null) 内容到 ''.

这是 TargetNullValue 的未记录行为还是这里有其他副作用?

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

最佳答案

这似乎是无证行为。如果你看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 将重置属性为空。

关于c# - 为什么 TargetNullValue 更新可为空的 Source,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36402291/

相关文章:

c# - 按需 IEnumerable 绑定(bind)到 ListBox

javascript - KnockoutJS,与 2D 数组的样式绑定(bind)?

c# - Windows 窗体组合框中的复杂数据绑定(bind)

c# - 如何使用 C# 启动具有特定 URL 的 Google Chrome 选项卡

c# - 是否可以编辑以下代码,以便也执行第二种方法?

c# - 如何将按钮模板中的内容居中并将鼠标事件保持在空白区域

c# - 对控件的通用 WPF 多线程访问

c# - 柱形图中的多个系列 asp.net 4.0

c# - 代码取决于构建类型?

WPF在单击复选框时传递多个参数