C# 使用代码删除 WPF 中的绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/186475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove binding in WPF using code
提问by Robert H?glund
I would like to use databinding when displaying data in a TextBox. I'm basically doing like:
我想在 TextBox 中显示数据时使用数据绑定。我基本上是这样做的:
public void ShowRandomObject(IRandomObject randomObject) {
Binding binding = new Binding {Source = randomObject, Path = new PropertyPath("Name")};
txtName.SetBinding(TextBox.TextProperty, binding);
}
I can't seem to find a way to unset the binding. I will be calling this method with a lot of different objects but the TextBox will remain the same. Is there a way to remove the previous binding or is this done automatically when I set the new binding?
我似乎找不到解除绑定的方法。我将使用许多不同的对象调用此方法,但 TextBox 将保持不变。有没有办法删除以前的绑定,还是在我设置新绑定时自动完成?
采纳答案by Pop Catalin
When available
有空的时候
BindingOperations.ClearBinding(txtName, TextBox.TextProperty)
For older SilverLight versions, but not reliable as stated in comments:
对于较旧的 SilverLight 版本,但如评论中所述不可靠:
txtName.SetBinding(TextBox.TextProperty, null);
C# 6.0 features enabled
已启用 C# 6.0 功能
this.btnFinish.ClearBinding(ButtonBase.CommandProperty);
回答by Arcturus
How about:
怎么样:
this.ClearValue(TextBox.TextProperty);
It's much cleaner I think ;)
我认为它更干净;)
回答by Ed Ball
Alternately:
交替:
BindingOperations.ClearBinding(txtName, TextBox.TextProperty)
回答by Bodekaer
How about just
刚刚怎么样
txtName.Text = txtName.Text;
You would have to set the value after clearing it anyways. This works in SL4 at least.
无论如何,您都必须在清除它后设置该值。这至少适用于 SL4。