I have a WPF application which uses Entity Framework to communicate with Database. I have 4 fields in database. My intention is whenever a user selects any particular column with the checkbox which is present inside a listview, I need to update the database IsChecked property on button click. but its not updating the backend..Please help
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; }
}
CS CODE:
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>
Binding works through the INotifyPropertyChanged interface being implemented by your class. You notify whenever a property changes.
Looking at your code, the bigger issue is that it isn't in a proper MVVM format. To learn and probably solve your issue you should try the MVVM (Model-View-ViewModel) approach to coding in WPF.
An example link that explains it:
http://www.codeproject.com/Articles/100175/Model-View-ViewModel-MVVM-Explained
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.