我有一个DataGrid,其ItemsSource设置为自定义对象的ObservableCollection,从窗口传递到包含DataGrid的usercontrol,虽然这个工作得很好,但是我希望在两个方向都注册更改如果我点击取消按钮,则可以取消我的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();
}
}
这是启动我的usercontrol并传递原始列表的代码,我将数据存储在其中。
Window window = new Window
{
Height = 200,
Width = 765,
Content = new UserControl1(list1: rectContourList),
};
window.ShowDialog();
答案 0 :(得分:0)
您可以将UpdateSourceTrigger=Explicit
设置为文本框。
<TextBox Name="tb1" Text="{Binding tbval, UpdateSourceTrigger=Explicit}"/>
然后在&#34; ok&#34;按钮单击更新源
private void OK_Button_Click(object sender, RoutedEventArgs e)
{
BindingExpression binding = tb1.GetBindingExpression(TextBox.TextProperty);
binding.UpdateSource();
}
并且&#34;取消&#34;如果你想在文本框中显示以前的值,只需设置上一个属性,否则你可以将它留空。
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