问题描述:

I am creating custom control for menu and I have ListBox in my control. Something like this:

<ListBox x:Name="MenuItemsList"

Grid.Row="1"

ItemsSource="{Binding ProgramList, Mode=OneWay}">

<ListBox.ItemTemplate>

<DataTemplate>

<StackPanel Margin="10">

<TextBlock Text="{Binding Title}" />

</StackPanel>

</DataTemplate>

</ListBox.ItemTemplate>

</ListBox>

Now when I want to catch Tap event, get properties from class and keep MVVM model. How can I catch this in MainPage.xaml.cs or in MainViewModel?

I have this code in my MainPage.xaml:

<controls:BottomMenu x:Name="BottomMenu" Canvas.Top="{Binding MenuCanvasTop}"

Width="480" Height="400">

</controls:BottomMenu>

I have prepare this code in my MainViewModel:

public RelayCommand<string> GoToSectionCommand

{

get

{

return goToArticleCommand

?? (goToArticleCommand = new RelayCommand<string>(

NavigateToSection));

}

}

But I don't know how can I call it. What's the best way?

Edit:

I tried to extend listbox:

 <ListBox x:Name="MenuItemsList"

Grid.Row="1"

ItemsSource="{Binding ProgramList, Mode=OneWay}">

<ListBox.ItemTemplate>

<DataTemplate>

<StackPanel Margin="10">

<Button Content="{Binding Title}"

Command="{Binding ListButtonClickCommand, Source={RelativeSource Self}}"

CommandParameter="{Binding Url}"/>

</StackPanel>

</DataTemplate>

</ListBox.ItemTemplate>

</ListBox>

With code-behind:

 public ICommand ListButtonClickCommand

{

get { return (ICommand)GetValue(ListButtonClickCommandProperty); }

set { SetValue(ListButtonClickCommandProperty, value); }

}

public static readonly DependencyProperty ListButtonClickCommandProperty =

DependencyProperty.Register("ListButtonClickCommand", typeof(ICommand), typeof(BottomMenu), new PropertyMetadata(null));

public BottomMenu()

{

InitializeComponent();

}

Then in MainPage.xaml:

 <controls:BottomMenu x:Name="BottomMenu" Canvas.Top="{Binding MenuCanvasTop}"

Width="480" Height="400"

ListButtonClickCommand="{Binding MenuItemButtonCommand}">

</controls:BottomMenu>

And in MainViewModel:

 private ICommand menuItemButtonCommand;

public ICommand MenuItemButtonCommand

{

get

{

return menuItemButtonCommand

?? (menuItemButtonCommand = new RelayCommand(

NavigateToArticleSection));

}

}

For now without luck. It's not working. RelayCommand isn't triggered.

Edit2

I guess the problem is with binding command in custom control but I don't know how to fix it.

网友答案:

You just need to bind to the UserControl -- using "RelativeSource Self" will bind to the Button, which is not what you want. You should be able to use an "ElementName" binding to locate the user control:

<UserControl x:Name="UserControlName" ... >

    ...

        <Button Content="{Binding Title}" 
                Command="{Binding ElementName=UserControlName,Path=ListButtonClickCommand}"
                CommandParameter="{Binding Url}"/>

    ...

</UserControl>
相关阅读:
Top