我正在学习 MVVM 和 WPF。我的项目中有一个 xaml
文件,它在后面的代码中有一个简单的点击事件处理程序。
现在我想在 MVVM 中做同样的事情。看了很多文章,也看了很多sof的答案。但是还是做不到。
谁能举一个简单的例子,其中一个按钮click事件是在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";
}
}
}
提前致谢。
最佳答案
您可以绑定(bind) 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 问题有一个使用静态绑定(bind)到 RoutedCommands 的示例:How to bind Close command to a button , 和 How to bind WPF button to a command in ViewModelBase?有一个稍微高级一点的例子。
关于c# - 使用 MVVM 在 WPF 中绑定(bind)命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16314828/