Reputation: 552
I am not using any particular library for this. I have a Listview in page and on its click I want to call a command named DemoCommand but as I bind my ViewModel to page it shows error command not found. My Xaml code is.
<Grid DataContext="{Binding OrdersObject}">
<ListView Grid.Row="1" ItemsSource="{Binding data.orders}" SelectionChanged="ListView_SelectionChanged" ItemTemplate="{StaticResource DueOrderTemplate}" ItemContainerStyle="{StaticResource StretchItemStyle}">
<Interactivity:Interaction.Behaviors>
<Core:EventTriggerBehavior EventName="SelectionChanged">
<Core:InvokeCommandAction CommandParameter="{Binding}" Command="{Binding DemoCommand}"/>
</Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
</ListView>
</Grid>
My binding code is
var OrdersObj = new ViewModels.OrdersVM();
await OrdersObj.GetOrders("cancel");
this.DataContext = OrdersObj;
And my View Model code is
class OrdersVM
{
public Models.DueOrderM OrdersObject { get; set; }
async public Task<Boolean> GetOrders(string order_type)
{
OrdersObject=//from API
}
RelayCommand<Models.OOrderM> _demoCommand;
public RelayCommand<Models.OOrderM> DemoCommand
{
get
{
if (_demoCommand == null)
{
_demoCommand = new RelayCommand<Models.OOrderM>((itemParam) =>
{
System.Diagnostics.Debug.WriteLine(itemParam);
});
}
return _demoCommand;
}
set { _demoCommand = value; }
}
}
Upvotes: 0
Views: 547
Reputation: 552
I was able to solve the problem myself after looking few examples none of which were working I got the solution myself according to which I needed to change only my Xaml code. updated code is
<ListView x:Name="lstItem" Grid.Row="1" ItemsSource="{Binding OrdersObject.data.orders}" ItemTemplate="{StaticResource DueOrderTemplate}" ItemContainerStyle="{StaticResource StretchItemStyle}">
<Interactivity:Interaction.Behaviors>
<Core:EventTriggerBehavior EventName="SelectionChanged">
<Core:InvokeCommandAction CommandParameter="{Binding SelectedItem, ElementName=lstItem}" Command="{Binding DemoCommand}"/>
</Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
</ListView>
Important thing I noted was naming of listview in command parameter and need to assign it using x:Name then it worked else it did not work. Hope it helps someone like me.
Upvotes: 1
Reputation: 6507
I would set DataContext
not in 'code behind' but in XAML
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
DataContext="{Binding ViewModel, Source={StaticResource ViewModelLocator}}"
d:DataContext="{Binding ViewModel, Source={StaticResource ViewModelLocator}}"
You set OrdersObject
as DataContext
to the Grid, so try RelativeSources
so your Command-Binding can see the ViewModel again.
Upvotes: 0