I have the following XAML in a WPF application. I would like to bind the button to an ICommand in a view model. For some reason, I am not able to see the command from my view.
this is in a 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 have any idea why I cannot bind to this command?
Thanks for any thoughts….
Looks like you are setting the
DataContextof theGridto theDataproperty of your ViewModel (or object). If the object that the Data property exposes doesn’t provide theSaveDatacommand, you’ll have the problem you’re describing. Remember theDataContextis inherited from the parent.If you require that the
DataContextis set in that manner, and still require the button to reference the parentDataContext, one option would be to use a RelativeSource to point to an element that has the ViewModel as theDataContext.In WPF you also have the option of making those commands static and using the
{x:Static}markup extension to reach it.Hope that helps.
EDIT: Here’s an example if your
<Grid>is contained in a<UserControl>.Also, I don’t know what your full XAML looks like, but I suspect that this can be simplified greatly by removing the
DataContexton theGridand Binding Data on theItemsControl(or whatever you’re using to show the list of objects).