简体   繁体   中英

WPF MouseMove on Grid, update Position on Object Instance

I want to bind the mousemove event to an instance of an object, and then update some properties in this object, how can I go about doing this? Below is my XAML:

<Window.Resources>
        <h:AdaptiveObject x:Key="adaptiveObject" />
    </Window.Resources>
   <Grid Name="Container"
            MouseMove="{Binding Source={StaticResource adaptiveObject}, Path=UpdateMouse}"

And here is the current C# I have, which is just concept and doesn't work, just want to show you what i'm attempting:

namespace AdaptiveViewport
{
    public class AdaptiveObject : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
        public int MouseX { get; set; }
        public int MouseY { get; set; }

        public UpdateMouse(object sender, MouseEventArgs e)
        {
            MouseX = e.X;
            MouseY = e.Y;
        }

Since MouseMove is a Event you cant simply bind it to a Command. One way to achieve what you want would be to use a method in your code-behind:

    <Grid MouseMove="OnMouseMove" Name="Container">...</Grid>

Code Behind:

private void OnMouseMove(object sender, MouseEventArgs e)
{
  var p = Mouse.GetPosition(Container);
  // p.X and p.Y are your coordinates here 
}

You can probably also use blend interactivity features but i couldn't figure out how to pass the coordinates to a bound command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM