❔ WPF - Use command of viewmodel instead of item on click
Hi,
I have a list of strings and display them as buttons. The list is held by a viewmodel and the viewmodel has a Command for the button click. Now, instead of creating an object for strings and add the Command to the items, I would like to have the Command at the viewmodel level.
6 Replies
The error is:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='Davaaron.BankOverview.ViewModels.Dialogs.NotificationDialogViewModel', AncestorLevel='1''. BindingExpression:Path=CloseDialogCommand; DataItem=null; target element is 'Button' (Name=''); target property is 'Command' (type 'ICommand')
Your AncestorType is a ViewModel. It's must always be a control tho
Oh okay.. so I have to add some kind of event to the items (buttons) and then listen in the NotificationDialogViewModel.. alright
Your VM method is a bit weird given it basically has the result twice:
RaiseRequestClose(new DialogResult(result, new DialogParameters($"parameter={parameter}")));
But besides that, your binding isn't correct. Indirect bindings go through controls first.
I prefer ElementName
bindings here because they're simpler to write.
So the Command
binds to the ItemsControl
, then into its DataContext
(your VM...which I assume is the one you want?).Thank you very much, that worked!! 🙂
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.