.net - 编辑对话框,带有 WPF 中的绑定(bind)和确定/取消

标签 .net wpf data-binding

我怎样才能有一个对话框来编辑具有绑定(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/

相关文章:

c# - 安装 CORS 后无法加载文件

.net - IQueryable<> 来自存储过程( Entity Framework )

c# - 如何从用户的视觉交互中生成 SQL?

android - 使用 Android 数据绑定(bind)动态切换布局元素的可见性。

c# - 如何在 Asp.Net Core 中设置日期绑定(bind)的文化?

c# - 使 Propertygrid 在运行时显示绑定(bind)的属性符号

.net - Wpf 用户控件和 MVVM

c# - 在较高 DPI 设置下将 Screen.PrimaryScreen.WorkingArea 转换为 WPF 尺寸

wpf - 打印 WPF FlowDocument

wpf - 如何在 WPF 中创建类似 UI 的 XY Controller