MVVMLight Command 绑定示例

本章讲述:在MVVMLight中,简单的Command命令绑定示例;

前端代码示例:两种绑定方式

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"    <!--引用库-->

<Window.DataContext>
        <vm:MainWindowVM/>
    </Window.DataContext>
    <StackPanel HorizontalAlignment="Left">
        <Button Margin="10" Width="100" Height="30" Content="MVVM1" Command="{Binding ShowMsgCommand}"></Button>
        <Button Margin="10" Width="100" Height="30" Content="MVVM2" Command="{Binding ButtonClickCommand}"></Button>
        <Button Margin="10" Width="100" Height="30" Content="MVVM2" Command="{Binding CloseCmd}"
                CommandParameter="{Binding RelativeSource={x:Static RelativeSource.Self}}"/>
<Button Style="{StaticResource ViewImagebtnStyleKey}" Margin="5 0 0 0" ToolTip="" Command="{Binding DelCommand,RelativeSource={RelativeSource TemplatedParent}}" CommandParameter="{Binding}">
	<Image  Height="20" Width="20"  Source="/DSViewer;component/Images/ImageList/delete.png" Stretch="Fill"/>
</Button>


        <Button Name="btn" Content="Button" Height="30" HorizontalAlignment="Left" Margin="10" VerticalAlignment="Top" Width="100">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <i:InvokeCommandAction Command="{Binding Command1}" CommandParameter="10" />
                </i:EventTrigger>
                <i:EventTrigger EventName="MouseMove">
                    <i:InvokeCommandAction Command="{Binding Command2}" CommandParameter="{Binding ElementName=btn}" />
                </i:EventTrigger>
                <i:EventTrigger EventName="MouseLeave">
                    <i:InvokeCommandAction Command="{Binding Command_MousLeave}" CommandParameter="{Binding ElementName=btn}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Button>

        <Image Name="imge" Width="25" Height="25" HorizontalAlignment="Center" Margin="10" Source="/CommandTest;component/Images/u1285.png">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="MouseEnter">
                    <i:InvokeCommandAction Command="{Binding Command_MouseEnter}" CommandParameter="{Binding ElementName=imge}"/>
                </i:EventTrigger>
                <i:EventTrigger EventName="MouseLeave">
                    <i:InvokeCommandAction Command="{Binding Command_ImageMouseLeave}" CommandParameter="{Binding ElementName=imge}"/>
                </i:EventTrigger>
                <i:EventTrigger EventName="MouseLeftButtonUp">
                    <i:InvokeCommandAction Command="{Binding Command_Click}" CommandParameter="{Binding ElementName=imge}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
            
        </Image>
    </StackPanel>

“CommandParameter="{Binding RelativeSource={x:Static RelativeSource.Self}}" ”表示:绑定的参数是自身;

“CommandParameter="{Binding ElementName=btn}" ”  表示:绑定一个控件,btn是控件名称;

“CommandParameter="10"  ” 表示:绑定参数是10;

后端逻辑代码

        private ICommand m_CloseCmd;
        public ICommand CloseCmd
        {
            get
            {
                return m_CloseCmd ?? (m_CloseCmd = new RelayCommand<Button>((bnt) =>
                {
                    bnt.Content = "Close";
                    MessageBox.Show("Close Window!");
                    App.Current.MainWindow.Close();
                }));
            }
        }

        private ICommand m_Command1;
        public ICommand Command1
        {
            get
            {
                return m_Command1 ?? (m_Command1 = new RelayCommand<string>((str) =>
                {
                    string param = str;
                    MessageBox.Show("参数 :" + param);
                }));
            }
        }

        private ICommand m_Command2;
        public ICommand Command2
        {
            get
            {
                return m_Command2 ?? (m_Command2 = new RelayCommand<Button>((btn) =>
                {
                    btn.Content = "setting";
                }));
            }
        }

        private ICommand m_Command_MousLeave;
        public ICommand Command_MousLeave
        {
            get
            {
                return m_Command_MousLeave ?? (m_Command_MousLeave = new RelayCommand<Button>((bnt) =>
                    {
                        bnt.Content = "Button";
                    }));
            }
        }


        private ICommand m_Command_MouseEnter;
        public ICommand Command_MouseEnter
        {
            get
            {
                return m_Command_MouseEnter ?? (m_Command_MouseEnter = new RelayCommand<Image>((img) =>
                    {
                        img.Source = BitmapFromUri(new Uri("pack://application:,,,/CommandTest;component/Images/u1128.png"));
                    }));
            }
        }

        private ICommand m_Command_ImageMouseLeave;
        public ICommand Command_ImageMouseLeave
        {
            get
            {
                return m_Command_ImageMouseLeave ?? (m_Command_ImageMouseLeave = new RelayCommand<Image>((img) =>
                    {
                        img.Source = BitmapFromUri(new Uri("pack://application:,,,/CommandTest;component/Images/u1285.png"));
                    }));
            }
        }

        private ICommand m_Command_Click;
        public ICommand Command_Click
        {
            get
            {
                return m_Command_Click ?? (m_Command_Click = new RelayCommand<Image>((img) =>
                    {
                        MessageBox.Show("Image click!");
                    }));
            }
        }

        static object lockObj = new object();
        public static System.Windows.Media.ImageSource BitmapFromUri(Uri source)
        {
            var bitmap = new System.Windows.Media.Imaging.BitmapImage();
            try
            {
                var temp = new System.Windows.Media.Imaging.BitmapImage(source);
                temp = null;
                lock (lockObj)
                {
                    bitmap.BeginInit();
                    bitmap.UriSource = source;
                    bitmap.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad;
                    bitmap.EndInit();
                }
            }
            catch { }
            return bitmap;
        }

 

在 WPF 应用程序中,使用 MVVM 模式时,常用的命令绑定方式是通过 RelayCommand,它是一个实现了 ICommand 接口的类,可以将其绑定到视图模型中的命令属性上。 下面是 RelayCommand 的使用示例: 首先,定义一个 RelayCommand 类: ```csharp public class RelayCommand : ICommand { private readonly Action _execute; private readonly Func<bool> _canExecute; public RelayCommand(Action execute) : this(execute, null) { } public RelayCommand(Action execute, Func<bool> canExecute) { _execute = execute ?? throw new ArgumentNullException(nameof(execute)); _canExecute = canExecute; } public bool CanExecute(object parameter) { return _canExecute == null || _canExecute(); } public void Execute(object parameter) { _execute(); } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } } ``` 这里的 RelayCommand 类有两个构造函数,第一个只接受一个 Action 类型的参数,用来执行命令;第二个构造函数接受一个 Func<bool> 类型的参数,用来判断命令是否可执行。在 CanExecute 方法中,如果 _canExecute 不为 null,就会调用它来判断命令是否可执行。 接下来,在视图模型中定义一个 RelayCommand 类型的属性,并在需要执行命令的方法中调用它: ```csharp public class MainViewModel : ViewModelBase { private readonly IDataService _dataService; public MainViewModel(IDataService dataService) { _dataService = dataService; LoadDataCommand = new RelayCommand(LoadData); } public ICommand LoadDataCommand { get; private set; } private void LoadData() { // 加载数据 } } ``` 最后,在 XAML 中绑定命令: ```xml <Button Content="Load Data" Command="{Binding LoadDataCommand}" /> ``` 这里的 Command 属性绑定到视图模型的 LoadDataCommand 属性上,当按钮被点击时,就会执行 LoadData 方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值