C# · 12月 27, 2021

c# – 使用MVVM在WPF中绑定命令

我正在学习MVVM和 WPF.我的项目中有一个xaml文件,在后面的代码中有一个简单的点击事件处理程序.

现在我想在MVVM中做同样的事情.我阅读了很多文章,并在sof中阅读了许多答案.但仍然无法做到这一点.

任何人都可以提供一个简单的例子,在MVVM中完成按钮点击事件.

编辑

<Window x:Class=”WhiteBalance.BaseCalWindow” xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml” xmlns:uc=”clr-namespace:NumberUpDownControl;assembly=NumberUpDownControl” xmlns:viewn=”clr-namespace:WhiteBalance.viewmodels” Title=”RefImgSettingWindow” Height=”900″ Width=”1000″ ResizeMode=”NoResize” BorderThickness=”4″> <Window.Resources> <viewn:DashBoardviewmodel x:Key=”demokey”></viewn:DashBoardviewmodel> </Window.Resources> <Grid x:Name=”gdParent” DataContext=”{StaticResource demokey}”> <Grid.ColumnDeFinitions> <ColumnDeFinition Width=”490″ /> <ColumnDeFinition Width=”488*” /> </Grid.ColumnDeFinitions> <Grid.RowDeFinitions> <RowDeFinition Height=”300″ /> <RowDeFinition Height=”300″ /> <RowDeFinition Height=”*” /> </Grid.RowDeFinitions> <StackPanel Grid.Row=”0″ Grid.Column=”0″> <Label Content=”{Binding Path=NAME,Mode=TwoWay}” Height=”28″ Name=”lblTest” /> <Button Content=”Capture” Height=”23″ Name=”btnCapture” Width=”75″ Command=”{Binding Path=SaveCommand}” Canvas.Left=”94″ Canvas.Top=”254″ /> </StackPanel> </Grid></Window>namespace WhiteBalance.viewmodels{ public class DashBoardviewmodel: ObservableObject { private string _name = “dsqdasd”; public string NAME { get { return _name; } set { _name = value; } } public ICommand SaveCommand { get; set; } private bool CanExecuteSaveCommand() { return true; // !string.IsNullOrEmpty(LastName); } private void CreateSaveCommand() { SaveCommand = new RelayCommand(SaveExecute,CanExecuteSaveCommand); } public void SaveExecute() { //Person.Save(_newPerson); NAME = “Changed Name”; } public DashBoardviewmodel() { //objModel.TestText = “This will change”; NAME = “TestName”; } }}

提前致谢.

解决方法 您可以将按钮的 Command属性绑定到返回 ICommand的任何属性. Prism实现了一个非常容易使用的非常方便的命令 DelegateCommand( here is a knock-off): public ICommand MyButtonClickCommand { get { return new DelegateCommand<object>(FuncToCall,FuncToEvaluate); }}private void FuncToCall(object context){ //this is called when the button is clicked}private bool FuncToEvaluate(object context){ //this is called to evaluate whether FuncToCall can be called //for example you can return true or false based on some validation logic return true;}<Button x:Name=”myButton” Command=”{Binding MyButtonClickCommand}” />

CodeProject示例How to use Commands in WPF有一个非常相似的代码示例,您可以轻松地完成.以前的Stack Overflow问题有一个使用静态绑定到:How to bind Close command to a button的RoutedCommands的例子,而How to bind WPF button to a command in ViewModelBase?有一个稍高一些的例子.