Really need your help with dynamic updating of the table.
Here is the table related with the INotifyPropertyChanged data "Table" and it will be described below that the DataContext is related with the mainVM. This way I am trying to display the table that may change during the execution of the program.
So here is my xaml part:
<DataGrid DataContext="{Binding Table, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}" Grid.Column="0" CanUserAddRows="false" AutoGenerateColumns="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinHeight="500">
<!-- Column Header Text & Bindings -->
<DataGrid.Columns>
<DataGridTemplateColumn >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox x:Name="checkBox" IsThreeState="False" IsChecked="{Binding IsChecked}" CommandParameter="{Binding Index}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header=" Port" Binding="{Binding Port}" MinWidth="70"/>
<DataGridTextColumn Header=" Host" Binding="{Binding Host}" MinWidth="70"/>
<DataGridTextColumn Header=" IPv4" Binding="{Binding IPV4}" MinWidth="70"/>
<DataGridTextColumn Header=" IPv6" Binding="{Binding IPV6}" MinWidth="70"/>
...
</DataGrid.Columns>
</DataGrid>
And that is the ViewModel code (ellipsis mean some omissions in the description of of class fields):
public class RowVM : ObservableObject
{
private string _port;
private string _host;
private string _ipv4;
private string _ipv6;
...
public string Port
{
get { return _port; }
set
{
_port = value;
OnPropertyChanged("Port");
}
}
...
}
public class MainViewModel : ObservableObject
{
public List<RowVM> Table { get; set; }
public MainViewModel()
{
Table = new List<RowVM>();
}
}
so it seems everything have been linked. But i can't see the items in the table after all :( Also have no exceptions.
here is my start body:
public partial class MainWindow : Window
{
MainViewModel _mainVM = new MainViewModel();
public MainWindow()
{
InitializeComponent();
DataContext = _mainVM;
RowVM row1 = new RowVM() { SN = "001" };
RowVM row2 = new RowVM() { SN = "010" };
_mainVM.Table.Add(row1);
_mainVM.Table.Add(row2);
}
}
Tell me please, what wrong am I doing?
P.S. the implementation of the INotifyPropertyChanged shell:
public class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
Your window doesn't know, when you add or remove times to your Table
. Instead of List<RowVM>
, you should use ObservableCollection<RowVM>
. It will invoke an event whenever an item is added or removed. This allows the GUI elements to realize they have to update themselves.