usercontrol button binding not responding to relaycommand on mainviewmodel

876 Views Asked by At

I have a MainWindow bound to its mainViewModel. inside the MainWindow I have a usercontrol defind like this

<vm:StatPanel DockPanel.Dock="Right" DataContext="{Binding Source={StaticResource viewModel}}" Loaded="StatPanel_Loaded" />

inside that usercontrol I have a datagrid with buttons. The goal is when the buttons are clicked to change a datagrid on the MainWindow xaml. this is what my usercontrol datagrid looks like

<Button Content="{Binding Path=sector}" Command="{Binding Path=filterGridCommand}"></Button>

when I run the application I get the following error.

System.Windows.Data Error: 40 : BindingExpression path error: 'filterGridCommand' property not found on 'object' ''mdSectorDetail' (HashCode=42410114)'. BindingExpression:Path=filterGridCommand; DataItem='mdSectorDetail' (HashCode=42410114); target element is 'Button' (Name=''); target property is 'Command' (type 'ICommand')

I am using a command relay that is located in the MainViewModel. My problem is I dont know how to reference that mainViewModel, i have tried several of the suggested solutions like the following

CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type }}}"

Please any suggestions will be helpful. Thank you.

2

There are 2 best solutions below

0
On

You can use snoop to find out what is your DataContext of Button. I think that in your case is wrong DataContext. If you give me all code of UserControl, I will write you a proper data bidning.

0
On

i use a empty "marker" interface for such things.

public interface IMyCommandDataContextHelper {}

the control/window which has the datacontext i wanna reach with relative source has to implement the empty interface.

 public partial class MainWindow : IMyCommandDataContextHelper 

then i can easily write my xaml with relative source

{Binding Path=DataContext.filterGridCommand, RelativeSource={RelativeSource AncestorType={x:Type local:IMyCommandDataContextHelper}}}

ps: Properties should be PascalCase :)

public ICommand FilterGridCommand {get{...}}