下面是一個完整的示例:
的VM:
public class MainViewModel : INotifyPropertyChanged
{
public ObservableCollection<Employee> Employees { get; set; }
public RelayCommand<Employee> FireCommand { get; set; }
private Employee selectedEmployee;
public Employee SelectedEmployee
{
get { return selectedEmployee; }
set
{
if (value != selectedEmployee)
{
selectedEmployee = value;
PropertyChanged(this, new PropertyChangedEventArgs("SelectedEmployee"));
FireCommand.RaiseCanExecuteChanged();
}
}
}
public MainViewModel()
{
Employees = new ObservableCollection<Employee>
{
new Employee{ Name = "Mickey Mouse", CanBeFired = true },
new Employee{ Name = "Barack Obama", CanBeFired = true },
new Employee{ Name = "Chuck Norris", CanBeFired = false /* Don't even try!!! */ }
};
foreach (Employee e in Employees)
{
e.PropertyChanged += (s, a) =>
{
if (a.PropertyName == "CanBeFired")
{
FireCommand.RaiseCanExecuteChanged();
}
};
}
FireCommand = new RelayCommand<Employee>(_ => Employees.Remove(SelectedEmployee), _ => SelectedEmployee != null && SelectedEmployee.CanBeFired);
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
的XAML:
<DataGrid ItemsSource="{Binding Employees}" SelectedValue="{Binding SelectedEmployee}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"></TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridCheckBoxColumn Binding="{Binding CanBeFired,UpdateSourceTrigger=PropertyChanged}"></DataGridCheckBoxColumn>
</DataGrid.Columns>
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="Fire" Command="{Binding FireCommand}">
</MenuItem>
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
注意,你並不需要一個泛型RelayCommand
因此可以忽略通用參數和lambda的_
參數。
我很困惑 - 這會給我在每一列中的相同的1項上下文菜單(即「火」),對不對?我需要爲不同的列有不同的上下文菜單。所有文本列,如果有幫助。因此,例如,在第一列中,我希望有一個上下文菜單,其中顯示「Fire」,但在第二列上我想要一個帶有「This」,「That」和「The Other」的3項上下文菜單。 – MarkV 2014-09-11 12:26:13
我會說ContextMenu必須關聯到DataTemplate中的TextBlock – rpaulin56 2016-04-28 13:59:52
@Pragmateek這很有幫助。你可以發佈RelayCommand的代碼嗎? – vdidxho 2018-03-01 13:55:39