我在DataGrid和对象之间有双向绑定。我想只在用户单击保存按钮时将DataGrid中所做的更改保存到对象。作为第一步,我设置UpdateSourceTrigger = Explicit。我希望当我将该属性设置为显式时不会发生绑定(因为我还没有调用UpdateSource()),但与我的期望相反,当我关闭并重新启动程序时,更改将绑定到对象。
为什么我的更改仍然绑定到我的对象设置?
这是我的xaml文件中的相关DataGrid代码:
<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>
答案 0 :(得分:1)
尝试使用DataGridTemplateColumn而不是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修改值时,它将不会触发。因此,最后,您将能够从代码中保存修改。