Reputation: 269
I am writing a Windows 10 Universal App, in which I have a ListView with its DataTemplate being a UserControl. Inside that UserControl there's a button whose click event I want to handle on my MainPage.
It's basically a list of contacts, and the button is supposed to remove a contact from the list when clicked, and have no idea how can I handle the UserControl's button click.
This is the XAML for the UserControl:
<UserControl
x:Class="DataBinding_Test1.ContactControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:DataBinding_Test1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="50">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Dictionary1.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<Grid Background="{ThemeResource AppBarBackgroundThemeBrush}"
HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Name="ContactIconTextBlock"
Style="{StaticResource IconStyle}"
Text="{x:Bind myContact.ContactIcon}"/>
<TextBlock Name="ContactNameTextBlock"
Grid.Column="1"
Style="{StaticResource LabelStyle}"
Text="{x:Bind myContact.ContactName}"
RelativePanel.RightOf="ContactIconTextBlock"/>
<Button Name="RemoveContactButton"
Grid.Column="2"
Content="X"
VerticalAlignment="Stretch"
Click="RemoveContactButton_OnClick"/>
</Grid>
</UserControl>
Which is inside this ListView:
<ListView
Name="ContactsListView"
Grid.Column="1"
ItemsSource="{x:Bind ContactList}"
ItemTemplate="{StaticResource ContactListDataTemplate}"
SelectionMode="None">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
How can I implement it?
Upvotes: 0
Views: 687
Reputation: 1050
You can add an event handler in the code behind of the user control and call it in the click event of the button.
code behind:
public event EventHandler OnRemoveContact;
private void RemoveContactButton_OnClick(object sender, RoutedEventArgs e)
{
//... your existing code here
OnRemoveContact?.Invoke(this, new EventArgs());
}
Now, you can use the event in your datatemplate into the code behind of your MainPage
Upvotes: 2