WPF 传递原事件参数 Drop 拖拽事件为例获取文件路径

▲ 拖拽文件到红色框,获取文件地址到右边。

需要额外引入一个程序集(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 Margin="15">
        <TextBlock Text="传递原事件参数" FontWeight="Bold" FontSize="16" Margin="0,5,0,5" ></TextBlock>
        <DockPanel x:Name="PassEventArg" >

            <Grid Height="50" Width="100" DockPanel.Dock="Left" >
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="Drop">
                        <mvvm:EventToCommand PassEventArgsToCommand="True" Command="{Binding DropCommand}" />
                    </i:EventTrigger>
                </i:Interaction.Triggers>

                <Border  BorderBrush="Red" BorderThickness="1" />
                <TextBlock Text="拖拽上传" TextAlignment="Center" VerticalAlignment="Center" FontSize="16" AllowDrop="True"  />
            </Grid>

            <Grid DockPanel.Dock="Right" VerticalAlignment="Center" Margin="5 0 0 0">
                <TextBox IsReadOnly="True" BorderThickness="0" TextWrapping="Wrap" AcceptsReturn="True" VerticalScrollBarVisibility="Auto"
                         Text="{Binding FileAdd,StringFormat='获取地址:\{0\}'}" ></TextBox>
            </Grid>

        </DockPanel>
    </StackPanel>

</Grid>

VIewModel:

public class MainVM : ViewModelBase
{
    #region 传递原事件参数

    private String fileAdd;
    /// <summary>
    /// 原事件参数
    /// </summary>
    public String FileAdd
    {
        get { return fileAdd; }
        set { fileAdd = value; RaisePropertyChanged(() => FileAdd); }
    }

    #endregion

    private RelayCommand<DragEventArgs> dropCommand;
    /// <summary>
    /// 传递原事件参数
    /// </summary>
    public RelayCommand<DragEventArgs> DropCommand
    {
        get
        {
            if (dropCommand == null)
                dropCommand = new RelayCommand<DragEventArgs>(e => ExecuteDrop(e));
            return dropCommand;
        }
        set { dropCommand = value; }
    }

    private void ExecuteDrop(DragEventArgs e)
    {
        FileAdd = ((System.Array)e.Data.GetData(System.Windows.DataFormats.FileDrop)).GetValue(0).ToString();
    }
}

传递原事件的参数,只要设置 PassEventArgsToCommand="True" 即可。




posted @   double64  阅读(837)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示