我有一个Datagrid,应该是我运行的SSH命令的列表。由于某种原因,它没有追加到列表中,只是替换了内容。这是XAML:
<DataGrid Name="CommandRows2" Margin="0,0,0,87" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridCheckBoxColumn Header="Delete" Binding="{Binding Delete}"/>
<DataGridTextColumn Header="Command" Binding="{Binding Command}" Width="200"/>
<DataGridTextColumn Header="Response" Binding="{Binding Response}" Width="*"/>
<DataGridTextColumn Header="Test Results" Binding="{Binding Results}" Width="70"/>
</DataGrid.Columns>
</DataGrid>
代码如下:
List<CommandGridItems> items = new List<CommandGridItems>();
private void ExecuteSingleCommand(object sender, RoutedEventArgs e)
{
string sshCommand = "hostname";
string returnedResults = "localhost";
items.Add(new CommandGridItems() { Delete = false, Command = sshCommand, Response = returnedResults, Results = "desc1" });
CommandRows2.ItemsSource = items;
}
public class CommandGridItems
{
public bool Delete { get; set; }
public string Command { get; set; }
public string Response { get; set; }
public string Results { get; set; }
}
答案 0 :(得分:1)
当您反复设置CommandRows2.ItemsSource = items;
时,第二和下一个分配都不会发生任何事情,因为值(items
)不变,它是相同的引用。
将List<CommandGridItems> items = new List<CommandGridItems>();
更改为ObservableCollection<CommandGridItems> items = new ObservableCollection<CommandGridItems>();
,只需添加新元素,而无需重新分配ItemsSource:
private void ExecuteSingleCommand(object sender, RoutedEventArgs e)
{
string sshCommand = "hostname";
string returnedResults = "localhost";
var element = new CommandGridItems() { Delete = false, Command = sshCommand, Response = returnedResults, Results = "desc1" }
items.Add(element);
}
一个单独添加的元素将显示在DataGrid中,因为ObservableCollection通过INotifyCollectionChanged
接口事件(CollectionChanged
)通知元素更改,而在这种情况下调用Refresh
会对性能造成影响。 / p>
INotifyCollectionChanged
和INotifyPropertyChanged
在WPF中是“必须做的”,用于通知UI有关ViewModel中的更改
答案 1 :(得分:0)
刷新Dim Range1 As Range
Set Range1 = .Range("J2:J" & LRow)
Range1.Value = Range1.Value
列表即可。
Items