1. 程式人生 > 其它 >WPF 事件轉命令 EventToCommand 以點選滑鼠獲取畫素座標為例

WPF 事件轉命令 EventToCommand 以點選滑鼠獲取畫素座標為例

空間有時候沒有 Command 的情況下可以用事件轉命令 EventToCommand 的方案解決。

▲ 滑鼠點選獲取到影象點選處的畫素座標值。

首先,還是需要額外引入一個程式集(System.Windows.Interactivity.dll)和相應名稱空間:

xmlns:mvvm="http://www.galasoft.ch/mvvmlight"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

XAML:

<Window.DataContext>
    <local:MainVM/>
</Window.DataContext>

<Grid>

    <StackPanel Orientation="Vertical">
        <Border BorderBrush="Red" BorderThickness="1" Margin="0 20 0 0">
            <Image x:Name="image" Width="1080" Height="460" Source="0.jpg" >
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="MouseLeftButtonDown">
                        <mvvm:EventToCommand Command="{Binding DoPointCommand}" PassEventArgsToCommand="True"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </Image>
        </Border>
        <TextBlock x:Name="txtCoord" Text="{Binding PointInfo, StringFormat='座標值:\{0\}'}" FontSize="20" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0 10 0 0"/>
    </StackPanel>

</Grid>

ViewModel:

public class MainVM : ViewModelBase
{
    private string _pointInfo;
    public string PointInfo
    {
        get { return _pointInfo; }
        set { _pointInfo = value; RaisePropertyChanged(() => PointInfo); }
    }

    private RelayCommand<MouseButtonEventArgs> _doPointCommand = null;
    public RelayCommand<MouseButtonEventArgs> DoPointCommand
    {
        get
        {
            if (_doPointCommand == null)
            {
                _doPointCommand = new RelayCommand<MouseButtonEventArgs>(e => DoPoint(e));
            }
            return _doPointCommand;
        }
        set { _doPointCommand = value; }
    }

    private void DoPoint(MouseButtonEventArgs e)
    {
        Image image = e.Source as Image;

        if (image == null)
        {
            return;
        }

        PointInfo = "(X=" + e.GetPosition(image).X.ToString("0") + ", Y=" + e.GetPosition(image).Y.ToString("0") + ")";
    }
}



參考:

https://www.cnblogs.com/wzh2010/p/6607702.html