基于wpf mvvm框架实现上位机代码
时间: 2023-09-20 11:04:33 浏览: 118
使用wpf技术开发的上位机程序框架
4星 · 用户满意度95%
以下是一个简单的基于 WPF MVVM 框架的上位机示例代码,实现了一个简单的计数器功能:
MainWindow.xaml:
```
<Window x:Class="WPFMVVMExample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF MVVM Example" Height="200" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Text="{Binding Count}" FontSize="48" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<Button Content="Increase" Command="{Binding IncreaseCountCommand}" Grid.Row="1" HorizontalAlignment="Center"/>
</Grid>
</Window>
```
MainWindow.xaml.cs:
```
using System.Windows;
namespace WPFMVVMExample
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
}
}
}
```
MainViewModel.cs:
```
using System.ComponentModel;
using System.Windows.Input;
namespace WPFMVVMExample
{
public class MainViewModel : INotifyPropertyChanged
{
private int _count;
public int Count
{
get { return _count; }
set
{
_count = value;
OnPropertyChanged("Count");
}
}
public ICommand IncreaseCountCommand { get; private set; }
public MainViewModel()
{
Count = 0;
IncreaseCountCommand = new RelayCommand(IncreaseCount);
}
private void IncreaseCount()
{
Count++;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
```
RelayCommand.cs:
```
using System;
using System.Windows.Input;
namespace WPFMVVMExample
{
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)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute();
}
public void Execute(object parameter)
{
_execute();
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}
}
```
这个示例代码实现了一个简单的计数器功能,通过按钮点击可以增加计数器的值。在 ViewModel 中定义了一个 Count 属性和 IncreaseCountCommand 命令,Count 属性绑定到 TextBlock 控件的 Text 属性上,IncreaseCountCommand 命令绑定到 Button 控件的 Command 属性上。使用了 RelayCommand 类实现了 ICommand 接口,处理按钮点击事件。在 MainWindow.xaml.cs 中设置了 DataContext 为 MainViewModel 的实例,实现了界面和 ViewModel 的绑定。
阅读全文