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
。换句话说,它有效地在 null
和 TargetNullValue
属性值之间建立了等效关系。然而,文档中根本没有提到这一点。
看这个例子:
<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/