在DataGrid和对象之间有双向绑定。我只想在用户单击保存按钮时将DataGrid中所做的更改保存到对象中。作为第一步,我设置UpdateSourceTrigger=Explicit。当我将该属性设置为显式时(因为我还没有调用UpdateSource()),我预计不会发生绑定,但与我的期望相反,当我关闭并重新启动程序时,更改被绑定到对象。
为什么我的更改仍然绑定到我的对象的设置?
这是我的相关DataGrid代码从我的xaml文件:
<DataGrid x:Name="DataGrid1" IsReadOnly="False"
AutoGenerateColumns="False" CanUserAddRows="False" SelectionUnit="Cell"
ItemsSource="{Binding data}">
<DataGrid.DataContext>
<Binding Source="{StaticResource myData}" UpdateSourceTrigger="Explicit"/>
</DataGrid.DataContext>
<DataGrid.Columns>
<DataGridTextColumn Header="Field" Binding="{Binding Path=name, Mode=TwoWay,
UpdateSourceTrigger=Explicit}" Width="Auto"/>
<DataGridTextColumn Header="Length of Field" Binding="{Binding Path=length, Mode=TwoWay,
UpdateSourceTrigger=Explicit}" Width="Auto"/>
</DataGrid.Columns>
</DataGrid>
尝试用datagridtemplatecoln代替TextColumn:
<Window x:Class="DataGridUpdateSourceTriggerOneWay.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DataGridUpdateSourceTriggerOneWay"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid x:Name="DataGrid1"
IsReadOnly="False"
AutoGenerateColumns="False"
CanUserAddRows="False"
SelectionUnit="Cell"
ItemsSource="{Binding data}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Field">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Name, Mode=TwoWay,
UpdateSourceTrigger=Explicit}" Width="Auto"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Length of Field">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Length, Mode=TwoWay,
UpdateSourceTrigger=Explicit}" Width="Auto"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
数据类在这里:
public class Data : INotifyPropertyChanged
{
private string _Name;
public string Name
{
get { return _Name; }
set
{
_Name = value;
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
private int _Length;
public int Length
{
get { return _Length; }
set
{
_Length = value;
PropertyChanged(this, new PropertyChangedEventArgs("Length"));
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
我的测试代码:
public partial class MainWindow : Window
{
public ObservableCollection<Data> data { get; set; }
public MainWindow()
{
InitializeComponent();
data = new ObservableCollection<Data>();
data.Add(new Data() { Name = "Data1", Length = 1 });
data.Add(new Data() { Name = "Data2", Length = 2 });
this.DataContext = this;
}
}
它只会在开始时到达PropertyChanged事件,在那之后,当从GUI修改值时,它不会触发。因此,最后,您将能够保存代码后的修改。