当我向数据库添加新行时,我正在尝试更新我的DataGrid
(名称:dgLicenseholder,绑定到一个ObservableCollection
。我正在使用)。MVVMLight
为什么这不起作用?
在我的ViewModel
中,我有一个public DelegateCommand RefreshCommand {get; private set; }
和一个方法:
private void Refresh() {
licenseHolders.Add(new LicenseHolders());
}
licenseHolders
是一个 ObservableCollection 列表,如下所示:
public ObservableCollection<LicenseHolders> licenseHolders { get; }
= new ObservableCollection<LicenseHolders>();
LicenseHolders
是 my 中的一个类Model
,它保存数据:
public class LicenseHolders {
public int ID { get; set; }
public string Foretaksnavn { get; set; }
// more like the above...
}
在 XAML 中,我将命令绑定到一个按钮,如下所示;
Command="{Binding RefreshCommand}"
CommandParameter="{Binding ElementName=dgLicenseHolder}"
我更新数据库的方法放置在 中ViewModel
,并由包含DataGrid
.
添加到数据库()
NewLicenseHolder nlh = Application.Current.Windows.OfType<NewLicenseHolder>().FirstOrDefault();
try {
using (SqlConnection sqlCon = new(connectionString))
using (SqlCommand sqlCmd = new(sqlString, sqlCon)) {
sqlCon.Open();
sqlCmd.Parameters.AddWithValue("@Foretaksnavn, nlh.txtForetaksnavn.Text.ToString());
// more of the above...
sqlCmd.ExecuteNonQuery();
}
}
问题一:
我绑定我的方式有什么问题RefreshCommand
?我添加到数据库的方法工作正常,但我必须重新打开窗口DataGrid
才能“捕捉”更改。
问题2:
如何绑定用于更新数据库的方法而不将其放入单击事件中?
更新的代码(尝试实施用户 ChrisBD 建议的解决方案)
LicenseHolder.cs - 持有者类(模型)
namespace Ridel.Hub.Model {
public class LicenseHolder {
public int ID { get; set; }
public string Foretaksnavn { get; set; }
public string Foretaksnummer { get; set; }
public string Adresse { get; set; }
public int Postnummer { get; set; }
public string Poststed { get; set; }
public string BIC { get; set; }
public string IBAN { get; set; }
public string Kontakt { get; set; }
public string Epost { get; set; }
public string Tlf { get; set; }
public string Kontonummer { get; set; }
}
}
RidelHubMainViewModel.cs (视图模型)
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using GalaSoft.MvvmLight.CommandWpf;
using Ridel.Hub.Model;
namespace Ridel.Hub.ViewModel {
public class RidelHubMainViewModel : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
public ICommand RefreshCommand { get; private set; }
public ObservableCollection<LicenseHolder> LicenseHolders { get; set; }
public RidelHubMainViewModel() {
RefreshCommand = new RelayCommand(this.ExecuteRefreshCommand);
LicenseHolders = new ObservableCollection<LicenseHolder>();
FillDataGridLicenseHolders();
}
private void ExecuteRefreshCommand() {
NewLicenseHolder nlh = Application.Current.Windows.OfType<NewLicenseHolder>().FirstOrDefault();
if (LicenseHolders == null) {
LicenseHolders = new ObservableCollection<LicenseHolder>();
} else {
AddToDB();
LicenseHolders.Clear();
LicenseHolders.Add(new LicenseHolder() { Foretaksnavn = nlh.txtForetaksnavn.Text.ToString() });
LicenseHolders.Add(new LicenseHolder() { Foretaksnummer = nlh.txtForetaksnr.Text.ToString() });
LicenseHolders.Add(new LicenseHolder() { Adresse = nlh.txtAdresse.Text.ToString() });
LicenseHolders.Add(new LicenseHolder() { Postnummer = Convert.ToInt32(nlh.txtPostnummer.Text.ToString()) });
LicenseHolders.Add(new LicenseHolder() { Poststed = nlh.txtPoststed.Text.ToString() });
LicenseHolders.Add(new LicenseHolder() { BIC = nlh.txtBIC.Text.ToString() });
LicenseHolders.Add(new LicenseHolder() { IBAN = nlh.txtIBAN.Text.ToString() });
LicenseHolders.Add(new LicenseHolder() { Kontakt = nlh.txtKontakt.Text.ToString() });
LicenseHolders.Add(new LicenseHolder() { Epost = nlh.txtEpost.Text.ToString() });
LicenseHolders.Add(new LicenseHolder() { Tlf = nlh.txtTlf.Text.ToString() });
LicenseHolders.Add(new LicenseHolder() { Kontonummer = nlh.txtKontonr.Text.ToString() });
}
}
public void FillDataGridLicenseHolders() {
// Initially populates my DataGrid with the Sql server table
try {
using (SqlConnection sqlCon = new(ConnectionString.connectionString))
using (SqlCommand sqlCmd = new("select * from tblLicenseHolder", sqlCon))
using (SqlDataAdapter sqlDaAd = new(sqlCmd))
using (DataSet ds = new()) {
sqlCon.Open();
sqlDaAd.Fill(ds, "tblLicenseHolder");
foreach (DataRow dr in ds.Tables[0].Rows) {
LicenseHolders.Add(new LicenseHolder {
ID = Convert.ToInt32(dr[0].ToString()),
Foretaksnavn = dr[1].ToString(),
Foretaksnummer = dr[2].ToString(),
Adresse = dr[3].ToString(),
Postnummer = (int)dr[4],
Poststed = dr[5].ToString(),
BIC = dr[6].ToString(),
IBAN = dr[7].ToString(),
Kontakt = dr[8].ToString(),
Epost = dr[9].ToString(),
Tlf = dr[10].ToString(),
Kontonummer = dr[11].ToString()
});
}
}
} catch (Exception ex) {
MessageBox.Show(ex.Message, "Message", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
private void OnPropertyChanged(string myLicenseHolder) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(myLicenseHolder));
}
private void OnLicenseHoldersPropertyChanged() {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("LicenseHolders"));
}
#region Slett løyvehaver
// How I delete rows from the DataGrid
private static bool RemoveFromDB(LicenseHolder myLicenseHolder) {
string sqlString = $"Delete from tblLicenseHolder where ID = '{myLicenseHolder.ID}'";
if (MessageBox.Show("Er du sikker på at du ønsker å slette valgt løyvehaver?", "Slett løyvehaver", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes) {
try {
using (SqlConnection sqlCon = new(ConnectionString.connectionString))
using (SqlCommand sqlCmd = new(sqlString, sqlCon)) {
sqlCon.Open();
sqlCmd.ExecuteNonQuery();
return true;
}
} catch {
return false;
}
} else {
return false;
}
}
private void RemoveLicenseHolderExecute(LicenseHolder myLicenseHolder) {
bool result = RemoveFromDB(myLicenseHolder);
if (result)
LicenseHolders.Remove(myLicenseHolder);
}
private RelayCommand<LicenseHolder> _removeLicenseHoldersCommand;
public RelayCommand<LicenseHolder> RemoveLicenseHoldersCommand => _removeLicenseHoldersCommand
??= new RelayCommand<LicenseHolder>(RemoveLicenseHolderExecute, RemoveLicenseHolderCanExecute);
private bool RemoveLicenseHolderCanExecute(LicenseHolder myLicenseHolder) {
return LicenseHolders.Contains(myLicenseHolder);
}
#endregion
public void AddToDB() {
string sqlString = "insert into tblLicenseHolder (Foretaksnavn, Foretaksnummer, Adresse, Postnummer, Poststed, BIC, IBAN, Kontakt, Epost, Tlf, Kontonummer) " +
"values (@Foretaksnavn, @Foretaksnummer, @Adresse, @Postnummer, @Poststed, @BIC, @IBAN, @Kontakt, @Epost, @Tlf, @Kontonummer)";
NewLicenseHolder nlh = Application.Current.Windows.OfType<NewLicenseHolder>().FirstOrDefault();
try {
using (SqlConnection sqlCon = new(ConnectionString.connectionString))
using (SqlCommand sqlCmd = new(sqlString, sqlCon)) {
sqlCon.Open();
if (string.IsNullOrEmpty(nlh.txtForetaksnavn.Text) || string.IsNullOrEmpty(nlh.txtForetaksnr.Text)
|| string.IsNullOrEmpty(nlh.txtAdresse.Text) || string.IsNullOrEmpty(nlh.txtPostnummer.Text)
|| string.IsNullOrEmpty(nlh.txtPoststed.Text) || string.IsNullOrEmpty(nlh.txtBIC.Text)
|| string.IsNullOrEmpty(nlh.txtIBAN.Text) || string.IsNullOrEmpty(nlh.txtKontakt.Text)
|| string.IsNullOrEmpty(nlh.txtEpost.Text) || string.IsNullOrEmpty(nlh.txtTlf.Text)
|| string.IsNullOrEmpty(nlh.txtKontonr.Text)) {
MessageBox.Show("Vennligst fyll ut alle tekstboksene.");
sqlCon.Close();
} else {
sqlCmd.Parameters.AddWithValue("@Foretaksnavn", nlh.txtForetaksnavn.Text.ToString());
sqlCmd.Parameters.AddWithValue("@Foretaksnummer", nlh.txtForetaksnr.Text.ToString());
sqlCmd.Parameters.AddWithValue("@Adresse", nlh.txtAdresse.Text.ToString());
sqlCmd.Parameters.AddWithValue("@Postnummer", nlh.txtPostnummer.Text);
sqlCmd.Parameters.AddWithValue("@Poststed", nlh.txtPoststed.Text.ToString());
sqlCmd.Parameters.AddWithValue("@BIC", nlh.txtBIC.Text.ToString());
sqlCmd.Parameters.AddWithValue("@IBAN", nlh.txtIBAN.Text.ToString());
sqlCmd.Parameters.AddWithValue("@Kontakt", nlh.txtKontakt.Text.ToString());
sqlCmd.Parameters.AddWithValue("@Epost", nlh.txtEpost.Text.ToString());
sqlCmd.Parameters.AddWithValue("@Tlf", nlh.txtTlf.Text.ToString());
sqlCmd.Parameters.AddWithValue("@Kontonummer", nlh.txtKontonr.Text.ToString());
sqlCmd.ExecuteNonQuery();
MessageBox.Show("Ny løyvehaver lagret. Husk å oppdatere listen.");
}
}
} catch (Exception ex) {
MessageBox.Show(ex.Message, "Message", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
}
}
查看,代码隐藏 - 父窗口 (LicenseHoldersWindow)
using System.Windows;
using System.Windows.Controls;
using Ridel.Hub.ViewModel;
namespace Ridel.Hub {
public partial class LicenseHoldersWindow : Window {
public LicenseHoldersWindow() {
InitializeComponent();
DataContext = new RidelHubMainViewModel();
}
private btnNew_Click(object sender, RoutedEventArgs e) {
NewLicenseHolder newLicenseHolder = new();
newLicenseHolder.ShowDialog();
}
}
}
视图,XAML - 父窗口 (LicenseHoldersWindow)
<Window
x:Class="Ridel.Hub.LicenseHoldersWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Ridel.Hub"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewmodel="clr-namespace:Ridel.Hub.ViewModel"
Title="License Holders"
d:DataContext="{d:DesignInstance Type=viewmodel:RidelHubMainViewModel}"
mc:Ignorable="d">
<!-- GUI stuff -->
<!-- also button to open new child-window "NewLicenseHolder" -->
<DataGrid
x:Name="dgLicenseHolder"
AutoGenerateColumns="False"
IsReadOnly="True"
ItemsSource="{Binding LicenseHolders, Mode=OneWay}"
SelectionChanged="dgLicenseHolder_SelectionChanged"
SelectionMode="Single">
查看,代码隐藏子窗口 (NewLicenseHolder)
using System.ComponentModel;
using System.Windows;
using Prism.Commands;
using Ridel.Hub.ViewModel;
namespace Ridel.Hub {
public partial class NewLicenseHolder : Window, INotifyPropertyChanged {
public NewLicenseHolder() {
InitializeComponent();
btnLogOut.Content = UserInfo.UserName;
DataContext = new RidelHubMainViewModel();
}
public event PropertyChangedEventHandler PropertyChanged;
private void btnLagre_Click(object sender, RoutedEventArgs e) {
// Button: Save new LicenseHolder
((RidelHubMainViewModel)DataContext).RefreshCommand.Execute(null);
this.Close();
}
}
}
视图,XAML- 子窗口 (NewLicenseHolder)
<Window
x:Class="Ridel.Hub.NewLicenseHolder"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:viewmodel="clr-namespace:Ridel.Hub.ViewModel"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
d:DataContext="{d:DesignInstance Type=viewmodel:RidelHubMainViewModel}"
mc:Ignorable="d">
<Button
Name="btnLagre"
Foreground="White"
HorizontalContentAlignment="Center"
Click="btnLagre_Click"
Command="{Binding RefreshCommand}"
Style="{DynamicResource ButtonWithRoundCornersGreen}" >
</Button>
好的,所以,如果你通读了所有这些:上帝保佑。如您所见,我在子表单中添加了新的行信息,单击保存,理想情况下,希望我的 DataGrid 然后自动更新(无需单击任何其他“刷新”或“更新”按钮。
现在发生的事情是,当我单击保存时,我收到一个错误:
System.NullReferenceException: 'Object reference not set to an instance of an object.' Local1 was null.
在我的AddToDB()
-method 中,在if-else statement
我检查没有一个文本框为空的地方。NewLicenseHolder class
所以我引用内部的方式显然有问题ViewModel
:
NewLicenseHolder nlh = Application.Current.Window.OfType<NewLicenseHolder>().FirstOrDefault();
如何正确引用它,并确保在我离开子表单并返回父表单时更新 DataGrid?
非常感谢,非常感谢任何指导以纠正我的想法!