The problem with the wpf command fails when a button is clicked

I have the following xaml in a wpf application. I would like to bind the button to ICommand in the view model. For some reason, I cannot see the command from my view. it is in the user control.

<Grid> <Grid.DataContext> <Binding x:Name="SettingsData" Path="Data" /> </Grid.DataContext> . . . <DockPanel Grid.Column="1"> <Button x:Name="SaveButton" DockPanel.Dock="Top" Height="25" HorizontalAlignment="Left" Margin="70 0 0 0" Command="{Binding Path=SaveData}" >Save Changes</Button> </DockPanel> </Grid> 

Here is my ICommand object -

 public ICommand SaveData { get { if (_saveData == null) { _saveData = new RelayCommand( param => this.saveData(), param => true ); } return _saveData ; } } 

Does anyone know why I can't get attached to this team?

Thanks for any thoughts ....

+4
source share
2 answers

It looks like you are setting the DataContext Grid to the Data property of your ViewModel (or object). If the object that provides the Data property does not provide the SaveData command, you will have a problem that you are describing. Remember that a DataContext is inherited from the parent.

If you require the DataContext to be set this way and still require the button to reference the parent DataContext, one option would be to use a RelativeSource to specify an element that has the ViewModel as the DataContext.

In WPF, you also have the option to make these commands static and use the {x: Static} markup extension to achieve this.

Hope this helps.

EDIT: Here's an example if your <Grid> contained in <UserControl> .

  <Button Command="{Binding Path=DataContext.SaveData, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}" ... /> 

Also, I don’t know what your full Xaml looks like, but I suspect it can be greatly simplified by removing the DataContext in the Grid and Binding Data on the ItemsControl (or what you use to display a list of objects).

+10
source

Looking at the error below, it looks like your DataContext on the DockPanel is associated with some kind of list:

I see this in the output window - BindingExpression path error: SaveData property not found in 'object' '' List`1 '

Please redefine the Source attribute in Binding if the DataContext is not at the top level.

0
source

All Articles