Question

I have a following wpf i need to fill my datagrid rows from text box values when user enters values in textboxes and press Add Vlan button.I am using MVVM pattern so i created an ICommand interface behind it: enter image description here

My C# code is :

#region ICommand

    public ICommand AddVlan
    { 
      get
      {
        if (_addVlan == null)
          _addVlan = new RelayCommand(() => this.AddVlans());

          return _addVlan;
      }

    }

    public ICommand RemoveVlan
    {
      get
      {
        if (_removeVlan == null)
          _removeVlan = new RelayCommand(() => this.RemoveVlans());

        return _removeVlan;
      }

    }
    #endregion //ICommand region end

The AddVlans() method will have actual event performer but i dont know how to perform event for displaying data in datagrid.

Xaml code is :

 <Button Grid.Column="3"
            Grid.Row="1"
            Content="Add VLAN"
            Margin="10,5,0,0"
            Style="{StaticResource AppButtons}"
            Command="{Binding AddVlan}"
            />      

    <Button Grid.Column="3" 
            Grid.Row="2"
            Content="Remove VLAN"
            Margin="10,5,0,0"
            Style="{StaticResource AppButtons}"
            Width="100"
            Command="{Binding RemoveVlan}"
            />

    <DataGrid Grid.Row="4"
              Grid.ColumnSpan="3"
              Height="200"
              Margin="10,10,0,0"> 

      <DataGrid.Columns>
      <DataGridTextColumn Header="VLAN Name"     />
      <DataGridTextColumn Header="VLAN ID"       />
      <DataGridTextColumn Header="IP" Width="100"/>
      <DataGridTextColumn Header="VLAN Ports" Width="100"/>
      </DataGrid.Columns>
    </DataGrid>
  </Grid>

Can anyone explain me how to do this ??

Was it helpful?

Solution

Implement INotifyPropertyChanged properly, create properties for every TextBox/Field/ComboBox and bind them TwoWay. Make sure the changes made in your GUI are successfully reflected to your ViewModel. That being said, you are able to control the data that the user of your application has put in.

You will need to place an ObservableCollection in your ViewModel bound to your DataGrid's ItemsSource in order to notify the View about the changes. In your AddVlans() function, simply add a new entry to this ObservableCollection by using the associated property and you are done. If you implemented INotifyPropertyChanged properly, the View should get notified about your added entry and therefore the entry would show up in your DataGrid.

If you don't know yet what I'm talking about, please consider reading about Binding in WPF first before continuing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top