我怎样才能有一个对话框来编辑具有绑定(bind)的类的属性,并在对话框中有 OK-Cancel?
我的第一个想法是这样的:
public partial class EditServerDialog : Window {
private NewsServer _newsServer;
public EditServerDialog(NewsServer newsServer) {
InitializeComponent();
this.DataContext = (_newsServer = newsServer).Clone();
}
private void ButtonClick(object sender, RoutedEventArgs e)
{
switch (((Button)e.OriginalSource).Content.ToString()) {
case "OK":
_newsServer = (NewsServer)this.DataContext;
this.Close();
break;
case "Cancel":
this.Close();
break;
}
}
}
在切换时,情况“OK”,DataContext包含正确的信息,但原来传递的NewsServer实例没有改变。
最佳答案
老问题,但我会为 future 的读者回答......
您必须设置 UpdateSourceTrigger="Explicit"
在您的绑定(bind)上,因此在用户单击“确定”之前它们不会更新实际源。然后在您的 OK 按钮处理程序上,您可以编写:
BindingExpression be = MyTextBox.GetBindingExpression(TextBox.TextProperty);
if (be!=null) be.UpdateSource();
此外,如果您想将绑定(bind)重置为初始状态使用
BindingExpression be = MyTextBox.GetBindingExpression(TextBox.TextProperty);
if (be!=null) be.UpdateTarget();
如果您的对话框很复杂,您可能希望递归地遍历其所有控件。
关于.net - 编辑对话框,带有 WPF 中的绑定(bind)和确定/取消,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2559819/