hello, it is necessary that the checkbox click command parameter be this checkbox itself and it was possible in the viewModel to read the checkbox Uid. as much as possible simplified the code ...
<ListBox ItemsSource="{Binding Collection}"> <ListBox.ItemTemplate> <DataTemplate> <CheckBox Command="{Binding CheckBoxCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self}}" Uid="{Binding Element.Id}"/> <!--ΠΏΡΠΈΠ±ΠΈΠ½Π΄ΠΈΠ»ΠΈ ΠΊ ΠΏΠΎΠ»Ρ id ΠΏΠΎΠ»Ρ Element ΠΈΠ· ΡΡΡΡΠΊΡΡΡΡ ΠΈΠ· ΠΊΠΎΡΠΎΡΡΡ
ΡΠΎΡΡΠΎΠΈΡ Collection --> </DataTemplate> </ListBox.ItemTemplate> </ListBox> RelayCommand:
public class RelayCommand<T> : ICommand { private readonly Action<T> _execute; private readonly Predicate<T> _canExecute; public event EventHandler CanExecuteChanged; public RelayCommand(Action<T> execute) : this(execute, null) { } public RelayCommand(Action<T> execute, Predicate<T> canExecute) { if (execute == null) throw new ArgumentNullException("ΠΏΡΠ΅Π΄ΠΈΠΊΠ°Ρ Π½Π΅ Π΄ΠΎΠ»ΠΆΠ΅Π½ Π±ΡΡΡ ΡΠ°Π²Π½ΡΠΌ Π½ΡΠ»Ρ"); _execute = execute; _canExecute = canExecute; } public bool CanExecute(object parameter) { return _canExecute == null ? true : _canExecute((T)parameter); } public void Execute(object parameter) { _execute((T)parameter); } public void RaiseCanExecuteChanged() { var handler = CanExecuteChanged; if (handler != null) { handler(this, EventArgs.Empty); } } } viewModel:
class ViewModel { /// <summary> /// ΠΊΠΎΠΌΠ°Π½Π΄Π° ΡΠ΅Π»ΡΠΊΠ° ΠΏΠΎ checkbox /// </summary> private ICommand checkBoxCommand = null; public ICommand CheckBoxCommand { get { if (checkBoxCommand == null) { checkBoxCommand = new RelayCommand<CheckBox>(AddData); } return checkBoxCommand; } } private void AddData(CheckBox o) { var df = ((CheckBox)o).Uid; int brackPoint = 0; } /// <summary> /// ΠΊΠΎΠ½ΡΡΡΡΠΊΡΠΎΡ /// </summary> public ViewModel() { } public ObservableCollection<Element> Collection { /**/ } }
Model (simplified):
Struct Element { public ObservableCollection<someClass> Collection { /**/ } public int Id { /**/ }; } I put a bryak in addData and click on checkBox - it does not go into addData, but there are no errors ... help solve the problem
Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, Path=DataContext.CheckBoxCommand}"- user227049CommandParameteryou sure that you need to transfer theCheckBox? Instead, it is better to sendDataContextimmediately:CommandParameter="{Binding}", and thenprivate void AddData(Element o) {var df = o.UId; int brackPoint = 0; }private void AddData(Element o) {var df = o.UId; int brackPoint = 0; }private void AddData(Element o) {var df = o.UId; int brackPoint = 0; }- user227049