【问题标题】:Cancel or Save changes made to a custom object in a DataGrid取消或保存对 DataGrid 中的自定义对象所做的更改
【发布时间】:2015-12-02 21:36:35
【问题描述】:

我有一个 DataGrid,它的 ItemsSource 设置为自定义对象的 ObservableCollection,它从窗口传递到包含 DataGrid 的用户控件,虽然这工作得很好,并且在两个方向上都注册了更改我想如果我单击取消按钮,则可以取消在我的 UserControl 中所做的任何更改。

有什么方法可以将我在 DataGrid 中所做的任何更改推迟到父窗口中的 ItemSource 吗?或者相反,如果我愿意,可以通过某种方式取消更改。任何帮助将不胜感激,这是我当前的代码;

   public UserControl1(ObservableCollection<ContourControl.RectangleContour> list1)
    {
        InitializeComponent();
        itemCollectionViewSource = (CollectionViewSource)(FindResource("ItemCollectionViewSource"));

        itemCollectionViewSource.Source = list1;

        //here i create some columns and bind the data

        DataGridViewer.ItemsSource = list1;
        DataGridViewer.AutoGenerateColumns = false;

    }

    private void Cancel(object sender, RoutedEventArgs e)
    {
        //if i click this i would like any changes to list1 to be reverted or ignored

        Window parentWindow = Window.GetWindow((DependencyObject)sender);
        if (parentWindow != null)
        {
            parentWindow.Close();
        }
    }

    private void OK(object sender, RoutedEventArgs e)
    {
        //if i click this i would like the changes to carry on to my list, as it currently does instantly

        Window parentWindow = Window.GetWindow((DependencyObject)sender);
        if (parentWindow != null)
        {
            parentWindow.Close();
        }
    }

这是启动我的用户控件并传递我存储数据的原始列表的代码。

                Window window = new Window
            {
                Height = 200,
                Width = 765,
                Content = new UserControl1(list1: rectContourList),
            };
            window.ShowDialog();

【问题讨论】:

标签: c# .net wpf wpfdatagrid


【解决方案1】:

您可以将UpdateSourceTrigger=Explicit设置为您的文本框。

 <TextBox Name="tb1" Text="{Binding tbval, UpdateSourceTrigger=Explicit}"/>

然后点击“确定”按钮更新源代码

 private void OK_Button_Click(object sender, RoutedEventArgs e)
        {
            BindingExpression binding = tb1.GetBindingExpression(TextBox.TextProperty);
            binding.UpdateSource();
        }

如果你想在文本框上显示之前的值,在“取消”上只需将之前的属性设置回来,否则你可以把它留空。

private void Cancel_Button_Click_1(object sender, RoutedEventArgs e)
        {
            //tbval is the property binded to Textbox
            tbval = tbval;
        }

https://msdn.microsoft.com/en-us/library/system.windows.data.binding.updatesourcetrigger.aspx

【讨论】:

    猜你喜欢
    • 2017-03-26
    • 2014-08-05
    • 1970-01-01
    • 2021-07-06
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多