我有一个包含字符串的文本框,只有当用户按下按钮时才必须绑定(bind)该字符串。在 XAML 中:
<Button Command="{Binding Path=PingCommand}" Click="Button_Click">Go</Button>
<TextBox x:Name="txtUrl" Text="{Binding Path=Url,UpdateSourceTrigger=Explicit, Mode=OneWay}" />
在代码隐藏中:
private void Button_Click(object sender, RoutedEventArgs e)
{
BindingExpression be = this.txtUrl.GetBindingExpression(TextBox.TextProperty);
be.UpdateTarget();
}
“be”始终为 NULL。为什么?
更新:
好的,这是经过大量尝试后的一些更新。
如果,我将 Mode 设置为 OneWay with Explicit update。我在 GetBindingExpression 的“be”对象中有一个 NullReferenceException。
如果,我使用显式更新将模式设置为无(默认 TwoWay)。我有获取值 (string.empty) 的绑定(bind),它每次都会删除文本框中的所有内容。
如果,我将模式设置为 OneWay,使用 PropertyChanged,当我在文本框中按下按键时,绑定(bind)的属性没有引发任何问题,一旦我单击按钮,“be”对象中就会出现 NULLReferenceException。
如果,我将模式设置为空(默认 TwoWay),使用 PropertyChanged 我有每次按下时都会提升的属性(好),但我不想每次用户按下键时都更改属性......但是仅当用户按下按钮时。
最佳答案
好吧,经过更多思考后我注意到:
BindingExpression be = this.txtUrl.GetBindingExpression(TextBox.TextProperty);
be.UpdateTarget();
有些不合逻辑,因为我不想更新目标,而是更新源。我只是将 be.Updatetarget() 更改为 be.UpdateSource();一切都适用于此 XAML:
<TextBox x:Name="txtUrl" Text="{Binding Path=Url, UpdateSourceTrigger=Explicit}">...
感谢所有帮助我解决这个问题的人。我给大家加了+1!谢谢
关于c# - 按下按钮时绑定(bind)(显式绑定(bind))始终将 BindingExpression 设置为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1266266/