J
J
Jaguar_sea2014-09-23 07:37:31
WPF
Jaguar_sea, 2014-09-23 07:37:31

How to properly organize adding and editing at the click of a button?

Hello, I'm trying to figure out Entity Framework.
I have two views in my project...

mainwindow

<Window x:Class="CashReg.Client.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local ="clr-namespace:CashReg.View.ViewModel"
        Title="MainWindow" Height="350" SizeToContent="Width" WindowStartupLocation="CenterScreen">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <ToolBar>
            <Button Content="Добавить" Command="{Binding Path=OpenChildBankWin}" />
            <Button Content="Исправить"/>
            <Button Content="Удалить" Command="{Binding Path=DeleteBank}"/>
        </ToolBar>
        <DataGrid ItemsSource="{Binding Banks}" 
                  AutoGenerateColumns="False" 
                  Grid.Row="1" 
                  IsReadOnly="True"
                  SelectedItem="{Binding SelectBank}">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding city}" Header="Город"/>
                <DataGridTextColumn Binding="{Binding Name}" Header="Название"/>
                <DataGridTextColumn Binding="{Binding bik}" Header="БИК"/>
                <DataGridTextColumn Binding="{Binding kor_acc}" Header="Корр. счет"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>


AddOrEditBank

<Window x:Class="CashReg.View.View.AddOrEditBank"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Добавление..." ResizeMode="CanResizeWithGrip"  SizeToContent="WidthAndHeight">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        
        <TextBlock Text="Город:" Grid.Row="0" Grid.Column="0" Margin="5"/>
        <TextBox Text="{Binding Path=CurrentBank.city, UpdateSourceTrigger=PropertyChanged}"  Grid.Row="0" Grid.Column="1"  Margin="5" Width="150"/>

        <TextBlock Text="Банк:" Grid.Row="1" Grid.Column="0"  Margin="5"/>
        <TextBox Text="{Binding Path=CurrentBank.Name, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1" Grid.Column="1"  Margin="5" Width="150"/>

        <TextBlock Text="БИК:" Grid.Row="2" Grid.Column="0"  Margin="5"/>
        <TextBox Text="{Binding Path=CurrentBank.bik, UpdateSourceTrigger=PropertyChanged}" Grid.Row="2" Grid.Column="1"  Margin="5" Width="150"/>

        <TextBlock Text="Корр. счет:" Grid.Row="3" Grid.Column="0"  Margin="5"/>
        <TextBox Text="{Binding Path=CurrentBank.kor_acc, UpdateSourceTrigger=PropertyChanged}" Grid.Row="3" Grid.Column="1"  Margin="5" Width="150"/>

        <Button Grid.Row="4" Grid.Column="0" Content="OK" IsDefault="True"  Margin="5" Command="{Binding Path=OkBankChildWin}"/>
        <Button Grid.Row="4" Grid.Column="1" Content="Отмена" IsCancel="True"  Margin="5" HorizontalAlignment="Left" Padding="7,0"/>
    </Grid>
</Window>


And the following code in the ViewModel
viewmodel

public class MainWindowViewModel : ViewModelBase
    {
        private CashRegContext DbContext;

        public ObservableCollection<Bank> Banks { get; private set; }

        public MainWindowViewModel()
        {
            DbContext = new CashRegContext();
            Banks = new ObservableCollection<Bank>(DbContext.Banks);
        }


        #region Получение выделенной строки
        private Bank selectBank;
        public Bank SelectBank
        {
            get
            {
                return this.selectBank;
            }
            set
            {
                this.selectBank = value;
                this.OnPropertyChanged("SelectBank");
            }
        }
        #endregion


        #region Новый банк
        private Bank currentBank;
        public Bank CurrentBank
        {
            get 
            {
                if (this.currentBank == null)
                    currentBank = new Bank();
                return this.currentBank; 
            }
            set
            {
                this.currentBank = value;
                this.OnPropertyChanged("CurrentBank");
            }
        }
        #endregion

        #region Открытие дочернего окна
        private RelayCommand _openChildBankWin;
        public RelayCommand OpenChildBankWin
        {
            get
            {
                if (_openChildBankWin == null)
                    _openChildBankWin = new RelayCommand(executeOpenChildBankWin);

                return _openChildBankWin;
            }
        }

        AddOrEditBank ChildBankWin;
        private void executeOpenChildBankWin(object parameter)
        {
            ChildBankWin = new AddOrEditBank(this);
            ChildBankWin.ShowDialog();
        }
        #endregion

        #region Нажитие кнопки ОК в диалоговом окне добавления банка
        private RelayCommand _okBankChildWin;
        public ICommand OkBankChildWin
        {
            get
            {
                if (_okBankChildWin == null)
                    _okBankChildWin = new RelayCommand(OkSaveChildWindowImplementation, CanExecuteAddBankCommand);

                return _okBankChildWin;
            }
        }

        private bool CanExecuteAddBankCommand(object obj)
        {
            if (string.IsNullOrEmpty(CurrentBank.city) ||
                string.IsNullOrEmpty(CurrentBank.Name) ||
                string.IsNullOrEmpty(CurrentBank.bik) ||
                string.IsNullOrEmpty(CurrentBank.kor_acc))
                return false;
            return true;
        }

        private void OkSaveChildWindowImplementation(object parameter)
        {
            Banks.Add(CurrentBank);
            DbContext.Banks.Add(CurrentBank);
            DbContext.SaveChanges();
            currentBank = null;
            ChildBankWin.Close();
        }
        #endregion

        #region Удаление строки
        private RelayCommand _deleteBank;
        public ICommand DeleteBank
        {
            get
            {
                if (_deleteBank == null)
                    _deleteBank = new RelayCommand(DeleteBankImplementation, CanExecuteDeleteBankCommand);

                return _deleteBank;
            }
        }

        private bool CanExecuteDeleteBankCommand(object obj)
        {
            if (SelectBank == null)
                return false;
            return true;
        }

        private void DeleteBankImplementation(object parameter)
        {
            if (MessageBox.Show("Удалить запись?",
                 "Удаление...",
                 MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                DbContext.Banks.Remove(SelectBank);
                Banks.Remove(SelectBank);
                SelectBank = null;
                DbContext.SaveChanges();
            }
        }
        #endregion

        protected override void OnDispose()
        {
            this.Banks.Clear();
        }


How to properly organize the "Add" and "Edit" events of a record? At the moment, the add-on works correctly. But I don’t understand how to make it so that when you click the “Edit” button, the same window is displayed as if you click the “Add” button, only with the fields filled in and with the “OK” button, binding which would lead to editing , not adding...?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri, 2014-09-23
@Jaguar_sea

Add bool IsNew field to ViewModel. You make a new command for editing.

private void executeOpenChildBankWin(object parameter)
        {
            IsNew = true;
            ChildBankWin = new AddOrEditBank(this);
            ChildBankWin.ShowDialog();
        }

private void OkSaveChildWindowImplementation(object parameter)
        {
            if(IsNew)
            {
                  Banks.Add(CurrentBank);
                  DbContext.Banks.Add(CurrentBank);
            }            
            DbContext.SaveChanges();
            ChildBankWin.Close();
        }

If you started writing mvvm, then dig about DelegateCommand.cs

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question