Silverlight call command from button within listbox item template
I have seen this question asked a few times but I have not seen been able to find a complete answer to my scenario.
Within my project I have a user control that I have created as a listbox item. Within this user control I have a button
<Button x:Name="DetailButton"
Grid.Column="1"
Width="107"
Height="23"
Margin="196,94,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Click="MoreDetail_Click"
Command="{Binding GetCFSDetailCommand}"
Content="View Details [+]" />
the button has a click event specific to the view this basically expands or collapses a grid row based upon the state of visibility. I used an event here since it was specific to the ui. This button also has a command which is called in the VM.
VM code
public class SearchViewModel : INotifyPropertyChanged
{
private DelegateCommand _getCFSDetailCommand;
public DelegateCommand GetCFSDetailCommand
{
get
{
if (this._getCFSDetailCommand == null)
this._getCFSDetailCommand = new DelegateCommand(GetCFSDetailCommandExecute, CanGetCFSDetailCommandExecute);
return this._getCFSDetailCommand;
}
}
p开发者_JS百科rivate void GetCFSDetailCommandExecute(object parameter)
{
//bind collection to model call here
}
The issue I am having is the command on the button is "lost" or never called when inside the listbox item I have the view bound to the vm and if I place this command on any other button within the view the command is called. Can anyone help me understand how to call a Command bound to button within a listbox item?
Thank you in advance
randyc,
In your original (first) post you was binding the CommandParameter
to a local data context of list item. In the second post you miss that binding, and I think it is impossible in the context of second port.
In your case I propose to use the Element to Element binding to bind to the GetCFSDetailCommand
command from the parent data context.
The issue in calling a command within the usercontrol as a listbox item is that the pattern is looking for the command within the context of the control. Apparently the listbox item jumps outside of the visual tree and so binding is not inherited.
To correct this I needed to explicitly set the data context of the button to the ViewModel. This was ultimately solved using the Element to Element binding which allowed me to point the datacontext of the user control to the main view that contained it.
Hope this helps
精彩评论