Skip to content

Instantly share code, notes, and snippets.

@damirarh
Created June 23, 2013 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save damirarh/5844520 to your computer and use it in GitHub Desktop.
Save damirarh/5844520 to your computer and use it in GitHub Desktop.
public static class AttachedProperties
{
public static DependencyProperty ItemClickCommandProperty =
DependencyProperty.RegisterAttached("ItemClickCommand",
typeof(ICommand),
typeof(AttachedProperties),
new PropertyMetadata(null, OnItemClickCommandChanged));
public static void SetItemClickCommand(DependencyObject target, ICommand value)
{
target.SetValue(ItemClickCommandProperty, value);
}
public static ICommand GetItemClickCommand(DependencyObject target)
{
return (ICommand)target.GetValue(ItemClickCommandProperty);
}
private static void OnItemClickCommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
var element = target as ListViewBase;
if (element != null)
{
// If we're putting in a new command and there wasn't one already
// hook the event
if ((e.NewValue != null) && (e.OldValue == null))
{
element.ItemClick += OnItemClick;
}
// If we're clearing the command and it wasn't already null
// unhook the event
else if ((e.NewValue == null) && (e.OldValue != null))
{
element.ItemClick -= OnItemClick;
}
}
}
static void OnItemClick(object sender, ItemClickEventArgs e)
{
GetItemClickCommand(sender as ListViewBase).Execute(e.ClickedItem);
}
}
<ListView IsItemClickEnabled="True"
ItemsSource="{Binding Items}"
local:AttachedProperties.ItemClickCommand="{Binding ItemClickedCommand}" />
public ViewModel()
{
ItemClickedCommand = new DelegateCommand<string>(ItemClicked);
}
public void ItemClicked(string item)
{
// react to the event
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment