我有一个使用Entity Framework与数据库通信的WPF应用程序。我在数据库中有4个字段。我的意图是每当用户选择列表视图中存在的复选框的任何特定列时,我需要在按钮点击时更新数据库IsChecked属性。但它没有更新后端..请帮助
public partial class Datagrid
{
public int Id { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public Nullable<bool> IsChecked { get; set; }
}
public partial class SampleDbContext : DbContext
{
public virtual DbSet<Datagrid> Datagrids { get; set; }
}
public partial class MainWindow : Window
{
public ObservableCollection<Datagrid> data { get; set; }
public List<Datagrid> lst = new List<Datagrid>();
private SampleDbContext db;
public MainWindow()
{
db = new SampleDbContext();
lst = db.Datagrids.ToList();
InitializeComponent();
additems();
}
public void additems()
{
data = new ObservableCollection<Datagrid>(lst);
this.DataContext = this;
}
private void btn_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Updated");
this.db.SaveChanges();
}
}
的Xaml:
<Grid>
<ListView Name="lstCode" ItemsSource="{Binding data}" >
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="Location" DisplayMemberBinding="{Binding Location}"/>
<GridViewColumn Header="IsActive" Width="70">
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox Name="chk" IsChecked="{Binding IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></CheckBox>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
<Button Name="btn" Height="23" Margin="0,0,201,85" Content="Update" HorizontalAlignment="Right" VerticalAlignment="Bottom" RenderTransformOrigin="1.333,3.85" Click="btn_Click" />
</Grid>
答案 0 :(得分:0)
绑定通过您的类实现的INotifyPropertyChanged接口工作。只要房产发生变化,您就会通知。
查看您的代码,更大的问题是它没有采用正确的MVVM格式。要学习并可能解决您的问题,您应该尝试使用MVVM(Model-View-ViewModel)方法在WPF中进行编码。
解释它的示例链接:
http://www.codeproject.com/Articles/100175/Model-View-ViewModel-MVVM-Explained