我有一个MainWindow包含DataGrid,还有一个Button Edit,
<DataGrid x:Name="EmpDataGrid"
Grid.Row="1"
AutoGenerateColumns="False"
ItemsSource="{Binding loadDataBinding,Mode=TwoWay}"
SelectedItem="{Binding CurrentCustomer}" Grid.ColumnSpan="2">
<DataGrid.Columns>
<DataGridTextColumn Header="CustmorID" Binding="{Binding ID}" />
<DataGridTextColumn Header="CustmorNom" Binding="{Binding nom}" />
<DataGridTextColumn Header="CustmorPrenom" Binding="{Binding prenom}" />
<DataGridTextColumn Header="CustmorReference" Binding="{Binding reference}" />
</DataGrid.Columns>
<Button
Content="Edit"
Command="{Binding Edit}"
CommandParameter="{Binding CurrentCustomer}" />
然后我调用Window Update,XAML Window Update:
<Button Command="{Binding UpdateCustomer}"
<TextBox x:Name="nom" Text="{Binding CustomerToAddObject.nom,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
<TextBox x:Name="prenom" Text="{Binding CustomerToAddObject.prenom,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" ></TextBox>
<TextBox x:Name="reference" Text="{Binding CustomerToAddObject.reference,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" ></TextBox>
我的ViewModel:
class ViewModel1 : ViewModelBase
{
Test1Entities context = new Test1Entities();
public ViewModel1()
{ using (Test1Entities context = new Test1Entities())
{
_loadDataBinding = new ObservableCollection<Custmor>(context.Custmor.ToList());
}
edit = new RelayCommand(start);
CustomerToAddObject = new Custmor();
updateCustomer = new RelayCommand(UpdateFunction);
}
private ICommand edit;
public ICommand Edit
{
get
{
return edit;
}
}
//To call Update Window:
private void start(object obj)
{
Update windowUpdate = new Update();
windowUpdate.Show();
}
private ICommand updateCustomer;
public ICommand UpdateCustomer
{
get { return updateCustomer; }
}
private void UpdateFunction(object obj)
{
MessageBox.Show(currentCustomer.nom);
MessageBox.Show(customerToAddObject.nom);
using (Test1Entities context = new Test1Entities())
{
Custmor cus = context.Custmor.Find(currentCustomer.ID);
cus.nom = customerToAddObject.nom;
cus.prenom = customerToAddObject.prenom;
cus.reference = customerToAddObject.reference;
context.SaveChanges();
}
}
// customerToAddObject
private Custmor customerToAddObject;
public Custmor CustomerToAddObject
{
get { return customerToAddObject; }
set { customerToAddObject = value; }
}
//CurrentCustomer
private Custmor currentCustomer;
public Custmor CurrentCustomer
{
get { return currentCustomer; }
set
{ currentCustomer = value;
OnPropertyChanged("CurrentCustomer");
}
}
感谢您的帮助,
答案 0 :(得分:1)
尝试将DataContext
窗口的Update
设置为ViewModel1
的同一个实例:
private void start(object obj)
{
Update windowUpdate = new Update();
windowUpdate.DataContext = this; //<--
windowUpdate.Show();
}
如果您要创建新实例,则显然需要初始化此实例的CurrentCustomer
属性。