MouseUpCommand fires only sporadically - wpf

I have created an attched property to bind the MouseUpCommand and the MouseDownCommand to my ViewModel. While the MouseDownCommand fires as it should, the MouseUpCommand only fires sporadically. Does anyone know what I am doing wrong?
Here is my XAML:
<ItemsControl ItemsSource="{Binding Page.Collection}" Grid.Row="1" Grid.Column="1"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas IsItemsHost="True" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Background="Blue"
local:MouseBehaviour.MouseUpCommand="{Binding ViewModel.MouseUpCommand}"
local:MouseBehaviour.MouseDownCommand="{Binding ViewModel.MouseDownCommand}"
local:MouseBehaviour.MouseMoveCommand="{Binding ViewModel.MouseMoveCommand}">
</Canvas>
Here is the MouseBehavior:
public class MouseBehaviour
{
#region MouseUp
public static readonly DependencyProperty MouseUpCommandProperty =
DependencyProperty.RegisterAttached("MouseUpCommand", typeof(ICommand), typeof(MouseBehaviour), new FrameworkPropertyMetadata(new PropertyChangedCallback(MouseUpCommandChanged)));
private static void MouseUpCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)d;
element.PreviewMouseUp += element_MouseUp;
}
static void element_MouseUp(object sender, MouseButtonEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
ICommand command = GetMouseUpCommand(element);
command.Execute(e);
}
public static void SetMouseUpCommand(UIElement element, ICommand value)
{
element.SetValue(MouseUpCommandProperty, value);
}
public static ICommand GetMouseUpCommand(UIElement element)
{
return (ICommand)element.GetValue(MouseUpCommandProperty);
}
#endregion
#region MouseDown
public static readonly DependencyProperty MouseDownCommandProperty =
DependencyProperty.RegisterAttached("MouseDownCommand", typeof(ICommand), typeof(MouseBehaviour), new FrameworkPropertyMetadata(new PropertyChangedCallback(MouseDownCommandChanged)));
private static void MouseDownCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)d;
element.PreviewMouseDown += element_MouseDown;
}
static void element_MouseDown(object sender, MouseButtonEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
ICommand command = GetMouseDownCommand(element);
command.Execute(e);
}
public static void SetMouseDownCommand(UIElement element, ICommand value)
{
element.SetValue(MouseDownCommandProperty, value);
}
public static ICommand GetMouseDownCommand(UIElement element)
{
return (ICommand)element.GetValue(MouseDownCommandProperty);
}
#endregion
}
I have tried using the normal mouse commands as well as the preview mouse commands. No difference.

If I break the MVVM pattern and just add events to the code behind the program works flawlessly:
private void ItemsControl_MouseUp(object sender, MouseButtonEventArgs e)
{
mainViewModel.ViewModel.MouseUp(e);
}
private void ItemsControl_MouseMove(object sender, MouseEventArgs e)
{
mainViewModel.ViewModel.MouseMove(e);
}
private void ItemsControl_MouseDown(object sender, MouseButtonEventArgs e)
{
mainViewModel.ViewModel.MouseDown(e);
}

Related

Depedency Property Not Updated

Dependency property of my UserControl not trigger.My property inside usercontrol named "MultiColumnComboBox"=>
public readonly DependencyProperty ItemSourceValueProperty = DependencyProperty.Register("ItemSourceValue", typeof(List<EmployeeModel>), typeof(MultiColumnComboBox), new PropertyMetadata(new List<EmployeeModel>(),TargetPropertyChanged));
public List<EmployeeModel> ItemSourceValue
{
get
{
return (List<EmployeeModel>)GetValue(ItemSourceValueProperty);
}
set
{
SetValue(ItemSourceValueProperty, value);
}
}
private static void TargetPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
}
my xaml=>
<r:MultiColumnComboBox ItemSourceValue="{Binding EmployeeList}"
Grid.Row="0"
Grid.Column="1"
Margin="2"/>
I already check this link=>Link 1 Link 2 but this is not work for me.

NavigateUrl binding and formatting issue

I have
<Hyperlink attachedProperty:HyperlinkExtensions.IsExternal="true">
<Hyperlink.NavigateUri>
<Binding Path="Name" StringFormat="http://anycoolsite.net/tag={0}" />
</Hyperlink.NavigateUri>
<TextBlock>
<TextBlock.Text>
<Binding Path="Title" StringFormat="http://anycoolsite.net/tag={0}" />
</TextBlock.Text>
</TextBlock>
</Hyperlink>
and an attached property for that
public class HyperlinkExtensions
{
public static bool GetIsExternal(DependencyObject obj)
{
return (bool)obj.GetValue(IsExternalProperty);
}
public static void SetIsExternal(DependencyObject obj, bool value)
{
obj.SetValue(IsExternalProperty, value);
}
public static readonly DependencyProperty IsExternalProperty =
DependencyProperty.RegisterAttached("IsExternal", typeof(bool), typeof(HyperlinkExtensions), new UIPropertyMetadata(false, OnIsExternalChanged));
private static void OnIsExternalChanged(object sender, DependencyPropertyChangedEventArgs args)
{
var hyperlink = sender as Hyperlink;
if ((bool)args.NewValue)
hyperlink.RequestNavigate += Hyperlink_RequestNavigate;
else
hyperlink.RequestNavigate -= Hyperlink_RequestNavigate;
}
private static void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
e.Handled = true;
}
}
When I try to get an url from e, I only have a bound Name part, which is in {0}.
How to get the formatted one (http://anycoolsite.net/anyboundname)?
For testblock text the binding and formatting works as expected
OK, changed my extension this way:
public class HyperlinkExtensions
{
public static string GetUrlFormat(DependencyObject obj)
{
return (string)obj.GetValue(UrlFormatProperty);
}
public static void SetUrlFormat(DependencyObject obj, string value)
{
obj.SetValue(UrlFormatProperty, value);
}
public static readonly DependencyProperty UrlFormatProperty =
DependencyProperty.RegisterAttached("UrlFormat", typeof(string), typeof(HyperlinkExtensions), new UIPropertyMetadata(string.Empty, OnUrlFormatChanged));
private static void OnUrlFormatChanged(object sender, DependencyPropertyChangedEventArgs args)
{
var hyperlink = sender as Hyperlink;
if (!string.IsNullOrEmpty((string) args.NewValue))
{
hyperlink.NavigateUri = new Uri(string.Format((string) args.NewValue, hyperlink.NavigateUri));
hyperlink.RequestNavigate -= Hyperlink_RequestNavigate;
hyperlink.RequestNavigate += Hyperlink_RequestNavigate;
}
else
{
hyperlink.RequestNavigate -= Hyperlink_RequestNavigate;
}
}
private static void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
e.Handled = true;
}
}
Usage:
<Hyperlink attachedProperty:HyperlinkExtensions.UrlFormat="https://anycoolsite.com/products/{0}" ToolTip="Click to open in browser">
<Hyperlink.NavigateUri>
<Binding Path="ProductName"/>
</Hyperlink.NavigateUri>
<TextBlock Text="{Binding Title}"/>
</Hyperlink>

Mouseover button binding in WPF

What technique could be used in WPF to show TextBlock Text based on the Button that has mouse over on it?
The UI is organized as follows:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<StackPanel>
<Button Content="Item1" Tag="This is the text for Item1"/>
<Button Content="Item2" Tag="This is the text for Item2"/>
<Button Content="Item3" Tag="This is the text for Item3"/>
</StackPanel>
<TextBlock Grid.Column="2" Margin="20,0,0,0" TextWrapping="Wrap" Text="This text should be shown based on the mouseovered button"/>
</Grid>
I was thinking to set the desired text to Tag of the Button but how to get that Tag to show on the mouse over event.
Notes:
I prefer to use individual Buttons here instead of ListBox or any other ItemsControl (the real application has more controls between these things etc.)
The application follows MVVM
I would prefer an approach other that setting the texts to UI directly (Tag of the Button)
For Mouse Move over,
Create an AttachedProperty for MouseMove and hook your list view with the property. The attached property can be used to any element in your application.
Attached Property
public class MouseBehaviour
{
public static readonly DependencyProperty MouseMoveCommandProperty =
DependencyProperty.RegisterAttached("MouseMoveCommand", typeof(ICommand), typeof(MouseBehaviour), new FrameworkPropertyMetadata(new PropertyChangedCallback(MouseMoveCommandChanged)));
private static void MouseMoveCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)d;
element.MouseMove += new MouseEventHandler(element_MouseMove);
}
static void element_MouseMove(object sender, MouseEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
ICommand command = GetMouseMoveCommand(element);
command.Execute(e);
}
public static void SetMouseMoveCommand(UIElement element, ICommand value)
{
element.SetValue(MouseMoveCommandProperty, value);
}
public static ICommand GetMouseMoveCommand(UIElement element)
{
return (ICommand)element.GetValue(MouseMoveCommandProperty);
}
}
XAML
xmlns:mousebehav="clr-namespace:your namespace"
<Button mousebehav:MouseBehaviour.MouseMoveCommand="{Binding MouseMoveCommand}">
VM
private RelayCommand _MouseMoveCommand;
public RelayCommand MouseMoveCommand
{
get
{
if (_MouseMoveCommand== null) return _MouseMoveCommand= new RelayCommand(param => Execute_MouseMoveCommand((MouseEventArgs)param));
return _MouseMoveCommand;
}
set { _MouseMoveCommand= value; }
}
private void Execute_MouseMoveCommand(MouseEventArgs param)
{
//your logic to expand or ??
}
Attached property for Mouse Leave,
public static readonly DependencyProperty MouseLeaveCommandProperty =
DependencyProperty.RegisterAttached("MouseLeaveCommand", typeof(ICommand), typeof(MouseBehaviour), new FrameworkPropertyMetadata(new PropertyChangedCallback(MouseLeaveCommandChanged)));
private static void MouseLeaveCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)d;
element.MouseLeave += new MouseEventHandler(element_MouseLeave);
}
static void element_MouseLeave(object sender, MouseEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
ICommand command = GetMouseLeaveCommand(element);
command.Execute(e);
}
public static void SetMouseLeaveCommand(UIElement element, ICommand value)
{
element.SetValue(MouseLeaveCommandProperty, value);
}
public static ICommand GetMouseLeaveCommand(UIElement element)
{
return (ICommand)element.GetValue(MouseLeaveCommandProperty);
}
VM
private RelayCommand _MouseLeaveCommand;
public RelayCommand MouseLeaveCommand
{
get
{
if (_MouseLeaveCommand== null) return _MouseLeaveCommand= new RelayCommand(param => Execute_MouseLeaveCommand((MouseEventArgs)param));
return _MouseLeaveCommand;
}
set { _MouseMoveCommand= value; }
}
private void Execute_MouseLeaveCommand(MouseEventArgs param)
{
//your logic to expand or ??
}
XAML
<Button mousebehav:MouseBehaviour.MouseLeaveCommand="{Binding MouseLeaveCommand}">

Handling Mouse Events in MVVM in WPF

I am Using MVVM with WPF. i am halted in a way, i want your views about this. i am firing Mouse Events using MouseBehaviour.cs class , Is there any other way to handle Mouse Events in MVVM WPF
using System.Windows;
using System.Windows.Input;
namespace Lovatts.MouseBehaviours
{
public class MouseBehaviour
{
#region MouseUp
public static readonly DependencyProperty MouseUpCommandProperty =
DependencyProperty.RegisterAttached("MouseUpCommand", typeof(ICommand), typeof(MouseBehaviour), new FrameworkPropertyMetadata(new PropertyChangedCallback(MouseUpCommandChanged)));
private static void MouseUpCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)d;
element.MouseUp += element_MouseUp;
}
static void element_MouseUp(object sender, MouseButtonEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
ICommand command = GetMouseUpCommand(element);
command.Execute(e);
}
public static void SetMouseUpCommand(UIElement element, ICommand value)
{
element.SetValue(MouseUpCommandProperty, value);
}
public static ICommand GetMouseUpCommand(UIElement element)
{
return (ICommand)element.GetValue(MouseUpCommandProperty);
}
#endregion
#region MouseDown
public static readonly DependencyProperty MouseDownCommandProperty =
DependencyProperty.RegisterAttached("MouseDownCommand", typeof(ICommand), typeof(MouseBehaviour), new FrameworkPropertyMetadata(new PropertyChangedCallback(MouseDownCommandChanged)));
private static void MouseDownCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)d;
element.MouseDown += element_MouseDown;
}
static void element_MouseDown(object sender, MouseButtonEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
ICommand command = GetMouseDownCommand(element);
command.Execute(e);
}
public static void SetMouseDownCommand(UIElement element, ICommand value)
{
element.SetValue(MouseDownCommandProperty, value);
}
public static ICommand GetMouseDownCommand(UIElement element)
{
return (ICommand)element.GetValue(MouseDownCommandProperty);
}
#endregion
#region MouseLeave
public static readonly DependencyProperty MouseLeaveCommandProperty =
DependencyProperty.RegisterAttached("MouseLeaveCommand", typeof(ICommand), typeof(MouseBehaviour), new FrameworkPropertyMetadata(new PropertyChangedCallback(MouseLeaveCommandChanged)));
private static void MouseLeaveCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)d;
element.MouseLeave += new MouseEventHandler(element_MouseLeave);
}
static void element_MouseLeave(object sender, MouseEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
ICommand command = GetMouseLeaveCommand(element);
command.Execute(e);
}
public static void SetMouseLeaveCommand(UIElement element, ICommand value)
{
element.SetValue(MouseLeaveCommandProperty, value);
}
public static ICommand GetMouseLeaveCommand(UIElement element)
{
return (ICommand)element.GetValue(MouseLeaveCommandProperty);
}
#endregion
#region MouseLeftButtonDown
public static readonly DependencyProperty MouseLeftButtonDownCommandProperty =
DependencyProperty.RegisterAttached("MouseLeftButtonDownCommand", typeof(ICommand), typeof(MouseBehaviour), new FrameworkPropertyMetadata(new PropertyChangedCallback(MouseLeftButtonDownCommandChanged)));
private static void MouseLeftButtonDownCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)d;
element.MouseLeftButtonDown += element_MouseLeftButtonDown;
}
static void element_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
ICommand command = GetMouseLeftButtonDownCommand(element);
command.Execute(e);
}
public static void SetMouseLeftButtonDownCommand(UIElement element, ICommand value)
{
element.SetValue(MouseLeftButtonDownCommandProperty, value);
}
public static ICommand GetMouseLeftButtonDownCommand(UIElement element)
{
return (ICommand)element.GetValue(MouseLeftButtonDownCommandProperty);
}
#endregion
#region MouseLeftButtonUp
public static readonly DependencyProperty MouseLeftButtonUpCommandProperty =
DependencyProperty.RegisterAttached("MouseLeftButtonUpCommand", typeof(ICommand), typeof(MouseBehaviour), new FrameworkPropertyMetadata(new PropertyChangedCallback(MouseLeftButtonUpCommandChanged)));
private static void MouseLeftButtonUpCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)d;
element.MouseLeftButtonUp += element_MouseLeftButtonUp;
}
static void element_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
ICommand command = GetMouseLeftButtonUpCommand(element);
command.Execute(e);
}
public static void SetMouseLeftButtonUpCommand(UIElement element, ICommand value)
{
element.SetValue(MouseLeftButtonUpCommandProperty, value);
}
public static ICommand GetMouseLeftButtonUpCommand(UIElement element)
{
return (ICommand)element.GetValue(MouseLeftButtonUpCommandProperty);
}
#endregion
#region MouseMove
public static readonly DependencyProperty MouseMoveCommandProperty =
DependencyProperty.RegisterAttached("MouseMoveCommand", typeof(ICommand), typeof(MouseBehaviour), new FrameworkPropertyMetadata(new PropertyChangedCallback(MouseMoveCommandChanged)));
private static void MouseMoveCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)d;
element.MouseMove += new MouseEventHandler(element_MouseMove);
}
static void element_MouseMove(object sender, MouseEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
ICommand command = GetMouseMoveCommand(element);
command.Execute(e);
}
public static void SetMouseMoveCommand(UIElement element, ICommand value)
{
element.SetValue(MouseMoveCommandProperty, value);
}
public static ICommand GetMouseMoveCommand(UIElement element)
{
return (ICommand)element.GetValue(MouseMoveCommandProperty);
}
#endregion
#region MouseRightButtonDown
public static readonly DependencyProperty MouseRightButtonDownCommandProperty =
DependencyProperty.RegisterAttached("MouseRightButtonDownCommand", typeof(ICommand), typeof(MouseBehaviour), new FrameworkPropertyMetadata(new PropertyChangedCallback(MouseRightButtonDownCommandChanged)));
private static void MouseRightButtonDownCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)d;
element.MouseRightButtonDown += element_MouseRightButtonDown;
}
static void element_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
ICommand command = GetMouseRightButtonDownCommand(element);
command.Execute(e);
}
public static void SetMouseRightButtonDownCommand(UIElement element, ICommand value)
{
element.SetValue(MouseRightButtonDownCommandProperty, value);
}
public static ICommand GetMouseRightButtonDownCommand(UIElement element)
{
return (ICommand)element.GetValue(MouseRightButtonDownCommandProperty);
}
#endregion
#region MouseRightButtonUp
public static readonly DependencyProperty MouseRightButtonUpCommandProperty =
DependencyProperty.RegisterAttached("MouseRightButtonUpCommand", typeof(ICommand), typeof(MouseBehaviour), new FrameworkPropertyMetadata(new PropertyChangedCallback(MouseRightButtonUpCommandChanged)));
private static void MouseRightButtonUpCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)d;
element.MouseRightButtonUp += element_MouseRightButtonUp;
}
static void element_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
ICommand command = GetMouseRightButtonUpCommand(element);
command.Execute(e);
}
public static void SetMouseRightButtonUpCommand(UIElement element, ICommand value)
{
element.SetValue(MouseRightButtonUpCommandProperty, value);
}
public static ICommand GetMouseRightButtonUpCommand(UIElement element)
{
return (ICommand)element.GetValue(MouseRightButtonUpCommandProperty);
}
#endregion
#region MouseWheel
public static readonly DependencyProperty MouseWheelCommandProperty =
DependencyProperty.RegisterAttached("MouseWheelCommand", typeof(ICommand), typeof(MouseBehaviour), new FrameworkPropertyMetadata(new PropertyChangedCallback(MouseWheelCommandChanged)));
private static void MouseWheelCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)d;
element.MouseWheel += new MouseWheelEventHandler(element_MouseWheel);
}
static void element_MouseWheel(object sender, MouseWheelEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
ICommand command = GetMouseWheelCommand(element);
command.Execute(e);
}
public static void SetMouseWheelCommand(UIElement element, ICommand value)
{
element.SetValue(MouseWheelCommandProperty, value);
}
public static ICommand GetMouseWheelCommand(UIElement element)
{
return (ICommand)element.GetValue(MouseWheelCommandProperty);
}
#endregion
}
}
Here is my Xaml Code
<Window x:Class="Lovatts.MouseBehaviours.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:MouseBehaviours="clr-namespace:Lovatts.MouseBehaviours" x:Name="RibbonWindow"
Width="640" Height="480" DataContext="{Binding Main, Source={StaticResource Locator}}">
<Grid>
<Rectangle Width="100" Height="100" Fill="Blue" MouseBehaviours:MouseBehaviour.MouseUpCommand="{Binding MouseUpCommand}">
</Rectangle>
<Rectangle Width="100" Height="100" x:Name="Rectangle" Fill="Red" MouseBehaviours:MouseBehaviour.MouseUpCommand="{Binding MouseUpCommand}" Margin="75,109,457,241">
</Rectangle>
</Grid>
</Window>
MainViewModel.cs
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Windows;
namespace MouseBehaviours.ViewModel
{
public class MainViewModel : ViewModelBase
{
private RelayCommand _mouseUpCommand;
public RelayCommand MouseUpCommand
{
get
{
if (_mouseUpCommand == null) return _mouseUpCommand = new RelayCommand(param => ExecuteMouseUp((MouseEventArgs)param));
return _mouseUpCommand;
}
set { _mouseUpCommand = value; }
}
private void ExecuteMouseUp(MouseEventArgs e)
{
Console.WriteLine("Mouse Up : " + e.GetPosition((IInputElement)e.Source));
}
}
public class RelayCommand : ICommand
{
#region Fields
private readonly Action<object> _execute;
private readonly Predicate<object> _canExecute;
private string _displayText;
public static List<string> Log = new List<string>();
private Action<object> action;
#endregion // Fields
#region Constructors
/// <summary>
/// Creates a new command that can always execute.
/// </summary>
/// <param name="execute">The execution logic.</param>
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
/// <summary>
/// Creates a new command.
/// </summary>
/// <param name="execute">The execution logic.</param>
/// <param name="canExecute">The execution status logic.</param>
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
: this(execute, canExecute, "")
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute, string displayText)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
_displayText = displayText;
}
public string DisplayText
{
get { return _displayText; }
set { _displayText = value; }
}
#endregion // Constructors
#region ICommand Members
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute(parameter);
}
#endregion // ICommand Members
}
//class MainViewModel
//{
//}
}
Instead of writing you own behavior and calling commands from it, you can leverage the EventTriggers and Interactivity to bind the event action to the command.
here is simple example of doing it
http://www.c-sharpcorner.com/Blogs/11789/example-of-eventtrigger-in-mvvm-application.aspx
as described in the example if you want to fire command on MouseUp event on your rectangle you can just do:
<Rectangle >
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseUp">
<i:InvokeCommandAction Command="{Binding MyCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Rectangle >
#harjeet you need to use the below structure for Image MouseUp i.e instead of using "Image" try to use "Hyperlink command property" in TextBlock:
<TextBlock Panel.ZIndex="990"
Canvas.Right="30"
Canvas.Left="498"
Canvas.Top="4">
<Hyperlink TextDecorations="None"
Command="{Binding CloseLoginSettingPopup}">
<Image Cursor="Hand"
x:Name="Pop2"
Source="/img/close1.png"
Height="40"
Width="40"
Panel.ZIndex="990"
Canvas.Right="30"
Canvas.Left="498"
Canvas.Top="4" />
</Hyperlink>
</TextBlock>
https://learn.microsoft.com/en-us/dotnet/api/system.windows.input.mouseaction
<Rectangle>
<Rectangle.InputBindings>
<MouseBinding MouseAction="LeftClick" Command="{Binding MyCommand}" />
</Rectangle.InputBindings>
</Rectangle>

Custom ItemsSource property for a UserControl

Does anyone know how to make a custom ItemsSource?
What I want to do is to make an itemsSource to my own UserControl so that it could be bound by ObservableCollection<>.
Also, I could know Whenever the number of items in the itemsSource updated, so as to do further procedures.
Thank you so much.
You may need to do something like this in your control
public IEnumerable ItemsSource
{
get { return (IEnumerable)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(UserControl1), new PropertyMetadata(new PropertyChangedCallback(OnItemsSourcePropertyChanged)));
private static void OnItemsSourcePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var control = sender as UserControl1;
if (control != null)
control.OnItemsSourceChanged((IEnumerable)e.OldValue, (IEnumerable)e.NewValue);
}
private void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
{
// Remove handler for oldValue.CollectionChanged
var oldValueINotifyCollectionChanged = oldValue as INotifyCollectionChanged;
if (null != oldValueINotifyCollectionChanged)
{
oldValueINotifyCollectionChanged.CollectionChanged -= new NotifyCollectionChangedEventHandler(newValueINotifyCollectionChanged_CollectionChanged);
}
// Add handler for newValue.CollectionChanged (if possible)
var newValueINotifyCollectionChanged = newValue as INotifyCollectionChanged;
if (null != newValueINotifyCollectionChanged)
{
newValueINotifyCollectionChanged.CollectionChanged += new NotifyCollectionChangedEventHandler(newValueINotifyCollectionChanged_CollectionChanged);
}
}
void newValueINotifyCollectionChanged_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
//Do your stuff here.
}
Use a DependencyProperty ItemsSource in your CustomControl and then bind to this DependencyProperty
This is the XAML-Code (Recognize the DataContext of the ListBox):
<UserControl
x:Name="MyControl">
<ListBox
DataContext="{Binding ElementName=MyControl}"
ItemsSource="{Binding ItemsSource}">
</ListBox>
</UserControl>
This is the CodeBehind:
public partial class MyCustomControl
{
public IEnumerable ItemsSource
{
get { return (IEnumerable)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(IEnumerable),
typeof(ToolboxElementView), new PropertyMetadata(null));
}
This is the Code, where you use your "MyCustomControl":
<Window>
<local:MyCustomControl
ItemsSource="{Binding MyItemsIWantToBind}">
</local:MyCustomControl>
</Window>
Simplified answer.
public IEnumerable ItemsSource
{
get => (IEnumerable)GetValue(ItemsSourceProperty);
set => SetValue(ItemsSourceProperty, value);
}
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(UserControl1), new PropertyMetadata(null, (s, e) =>
{
if (s is UserControl1 uc)
{
if (e.OldValue is INotifyCollectionChanged oldValueINotifyCollectionChanged)
{
oldValueINotifyCollectionChanged.CollectionChanged -= uc.ItemsSource_CollectionChanged;
}
if (e.NewValue is INotifyCollectionChanged newValueINotifyCollectionChanged)
{
newValueINotifyCollectionChanged.CollectionChanged += uc.ItemsSource_CollectionChanged;
}
}
}));
private void ItemsSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
// Logic Here
}
// Do Not Forget To Remove Event On UserControl Unloaded
private void UserControl1_Unloaded(object sender, RoutedEventArgs e)
{
if (ItemsSource is INotifyCollectionChanged incc)
{
incc.CollectionChanged -= ItemsSource_CollectionChanged;
}
}

Resources