[英]Cancel or Save changes made to a custom object in a DataGrid
我有一个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();
您可以将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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.