从文本框值填充数据网格行?

时间:2014-04-25 12:05:41

标签: c# wpf mvvm datagrid icommand

我有一个以下的wpf我需要在用户在文本框中输入值时按文本框值填充我的数据网格行并按Add Vlan按钮。我正在使用MVVM模式,因此我在其后面创建了一个ICommand接口: enter image description here

我的C#代码是:

#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

AddVlans()方法将具有实际的事件执行者,但我不知道如何执行事件以在datagrid中显示数据。

Xaml代码是:

 <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>

谁能解释我怎么做?

1 个答案:

答案 0 :(得分:0)

正确实施INotifyPropertyChanged,为每个TextBox / Field / ComboBox创建属性并绑定它们 TwoWay 。确保GUI中所做的更改已成功反映到ViewModel中。话虽这么说,您可以控制应用程序用户输入的数据。

您需要在ViewModel中放置ObservableCollection绑定到DataGrid的ItemsSource,以便通知View有关更改。在AddVlans()函数中,只需使用关联的属性向此ObservableCollection添加新条目即可完成。如果您正确实施了INotifyPropertyChanged,则视图应该会收到有关您添加的条目的通知,因此该条目会显示在您的DataGrid中。

如果您还不知道我在说什么,请在继续之前先考虑在WPF中阅读绑定