Created
June 23, 2013 10:20
-
-
Save damirarh/5844520 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<ListView IsItemClickEnabled="True" | |
ItemsSource="{Binding Items}" | |
local:AttachedProperties.ItemClickCommand="{Binding ItemClickedCommand}" /> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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