Home > OS >  WPF .NET Core - how to find source of dependency property changed event?
WPF .NET Core - how to find source of dependency property changed event?

Time:10-19

I need to run code on ListViewItem mouse over event. I tried several solutions which none worked for me.

I came up with this:

        private void ProcessListItems()
        {
            foreach (var item in settings.items)
            {
                var i = lst.ItemContainerGenerator.ContainerFromItem(item) as ListViewItem;
                if (i == null)
                    continue;

                BindingOperations.SetBinding(this, ItemMouseOverProperty, new Binding
                {
                    Path = new PropertyPath(ListViewItem.IsMouseOverProperty),
                    Source = i 
                });
            }
        }

        public bool ItemMouseOver
        {
            get { return (bool)GetValue(ItemMouseOverProperty); }
            set { SetValue(ItemMouseOverProperty, value); }
        }

        public static readonly DependencyProperty ItemMouseOverProperty =
            DependencyProperty.Register("ItemMouseOver", typeof(bool), typeof(MainWindow), new PropertyMetadata(false, OnItemMouseOverChanged));

        static void OnItemMouseOverChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
        }

Once all items are added to the listview I bind each item ItemMouseOverProperty to my own dep prop ItemMouseOverProperty.

Now I need to find which ListViewItem triggered it..

In short: I bind one dep property to another. I want to find out which source object raised the changed event.

CodePudding user response:

The context of your code is not clear. Are you extending ListView or is this code-behind?

Generally, you can attach event handlers to the ListViewItem.MouseEnter event by adding a EventSetter to the style:

<ListView>
  <ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
      <EventSetter Event="MouseEnter" Handler="ListViewItem_MouseEnter" />
    </Style>
  </ListView.ItemContainerStyle>
</ListView>

private void ListViewItem_MouseEnter(object sender, MouseEventArgs e)
{
   var mouseOverItem = sender as ListViewItem;
}

Depending on your exact context, you can also define triggers and trigger on ListBoxItem.IsMouseOver.

  • Related