我通过ICommand向ObservableCollection添加项目时遇到问题。 第二个窗口用于编辑此ObservableCollection。 当我添加新项目时,第二个窗口中的ListView显示新项目,但第一个窗口不显示。 如何从我的命令中添加我的Obseravle Collection?
这是我的ObservableCollection:
public class ProductExtrasObservableCollection : ObservableCollection<ProductViewModel>
{
public AddToExtrasObservableCollectionCommand AddToExtrasObservableCollectionCommand { get; set; }
public DeleteExtrasProductCommand DeleteExtrasProductCommand { get; set; }
public ProductExtrasObservableCollection() : base()
{
AddToExtrasObservableCollectionCommand = new AddToExtrasObservableCollectionCommand(this);
DeleteExtrasProductCommand = new DeleteExtrasProductCommand(this);
Add(new ProductViewModel(new Product { Name = "Sugar", Price = 0.05, IsDrink = false }) { IsChecked = false } );
Add(new ProductViewModel(new Product { Name = "Milk", Price = 0.2, IsDrink = false }) { IsChecked = false });
Add(new ProductViewModel(new Product { Name = "Cream", Price = 0.1, IsDrink = false }) { IsChecked = false });
Add(new ProductViewModel(new Product { Name = "Canela", Price = 0.15, IsDrink = false }) { IsChecked = false });
}
}
}
这是我的班级命令:
public class AddToExtrasObservableCollectionCommand : ICommand
{
ProductExtrasObservableCollection Collection { get; set; }
public AddToExtrasObservableCollectionCommand(ProductExtrasObservableCollection Coll)
{
this.Collection = Coll;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
Collection.Add(new ProductViewModel(parameter as Product));
}
}
这是按钮的XAML:
<Button
Content="Add to Extras"
HorizontalAlignment="Left"
Margin="458,184,0,0"
VerticalAlignment="Top"
Width="88"
Height="60"
Command="{Binding AddToExtrasObservableCollectionCommand, Source={StaticResource ExtrasData}}"
CommandParameter="{Binding NewProduct, Source={StaticResource ViewModel}}" />