I am trying to bind a CommandParameter to a SelectedItem property of a DataGrid. Actually, the method is called only one time at the Window invocation.
This is what I usually do with Silverlight 5 which works pretty well.
<Button Command="{Binding DeleteProductCommand}" CommandParameter="{Binding ElementName=ProductDataGrid, Path=SelectedItem}"/>
...
<sdk:DataGrid x:Name="ProductDataGrid" AutoGenerateColumns="False" IsReadOnly="True" ItemsSource="{Binding ProductsCollection}">
...
I have read in the following post about the way commands are handled between SL and WPF. This is actually 4 years old. So I was just wondering if Microsoft released an update for this problem.
To cope with this problem I had to add a custom method called RaiseCanExecuteChanged in my command to fire the CanExecuteChanged event. Then I added a property in my ViewModel. I call the RaiseCanExecuteChanged method from the set accessor. Then I implemented the INotifyPropertyChanged interface in my ViewModel to warn the UI when the SelectedProduct property changes.
class MainVM : INotifyPropertyChanged
{
private Product _SelectedProduct;
public Product SelectedProduct
{
get
{
return this._SelectedProduct;
}
set
{
this._SelectedProduct = value;
this._PropertyChanged();
this.DeleteProductCommand.RaiseCanExecuteChanged();
}
}
private void _PropertyChanged([CallerMemberNameAttribute] string PropertyName = "")
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
...
}
XAML
<Button Command="{Binding DeleteProductCommand}" CommandParameter="{Binding SelectedProduct"/>
...
<sdk:DataGrid x:Name="ProductDataGrid" AutoGenerateColumns="False" IsReadOnly="True" ItemsSource="{Binding ProductsCollection}" SelectedItem="{Binding SelectedProduct}">
I would like to know if there is a better solution than that. Actually I tried the solution from the post I mentioned earlier but I have slight lags with the UI as it refreshes all the bindings of the Window.
Any help would be much appreciated !