【发布时间】:2020-02-23 17:03:06
【问题描述】:
我刚开始做 MVVM,因为听说过它的很多好处:
- 清洁码
- 可重用代码
- 更好的代码组织
因此开始执行通常的“代码隐藏”以确保我的代码正常工作,然后应用 MVVM 对其进行清理。 所以这是我的“背后代码”示例之一:
private const int LED_PIN = 17, RELAY_PIN = 27;
private GpioPin LEDpin, RELAYpin;
private bool InitGPIO(TextBlock txt)
{
var gpio = GpioController.GetDefault();
// Show an error if there is no GPIO controller
if (gpio == null)
{
txt.Text = "There is no GPIO controller on this device.";
txt.Foreground = new SolidColorBrush(Colors.Red);
return false;
}
txt.Text = "GPIO controller initialized correctly.";
txt.Foreground = new SolidColorBrush(Colors.Green);
LEDpin = gpio.OpenPin(LED_PIN);
RELAYpin = gpio.OpenPin(RELAY_PIN);
LEDpinValue = GpioPinValue.Low;
RELAYpinValue = GpioPinValue.High;
LEDpin.Write(LEDpinValue);
RELAYpin.Write(RELAYpinValue);
LEDpin.SetDriveMode(GpioPinDriveMode.Output);
RELAYpin.SetDriveMode(GpioPinDriveMode.Output);
return true;
}
要使用这个“InitGPIO”方法,我必须提供:
- 固定“int”引脚。
- GpioPin 类型。
- GpioPinValue 类型。
- 显示错误的文本块。
我已经创建了一个 ViewModelBase 和用于读取它的简化方法:
public class ViewModelBase
{
public InitGpioCommand InitGpiocommand { get; set; }
public ViewModelBase()
{
this.InitGpiocommand = new InitGpioCommand(this);
}
public bool InitGPIO(DigitalControl dc)
{
var gpio = GpioController.GetDefault();
// Show an error if there is no GPIO controller
if (gpio == null)
{
dc.Status.Text = "There is no GPIO controller on this device.";
dc.Status.Foreground = new SolidColorBrush(Colors.Red);
return false;
}
dc.Status.Text = "GPIO controller initialized correctly.";
dc.Status.Foreground = new SolidColorBrush(Colors.Green);
dc.DevicePin = gpio.OpenPin(dc.PinNumber);
dc.PinValue = GpioPinValue.Low;
dc.DevicePin.Write(dc.PinValue);
dc.DevicePin.SetDriveMode(GpioPinDriveMode.Output);
return true;
}
}
一切都在这个模型中被总结了:
public class DigitalControl
{
public TextBlock Status { get; set; }
public GpioPin DevicePin { get; set; }
public GpioPinValue PinValue { get; set; }
public int PinNumber { get; set; }
}
和我当前触发 InitGPIO 方法的按钮:
<Button x:Name="FirstLightTest"
Content="Test"
Command="{Binding InitGPIO,Source={StaticResource viewmodel}}">
</Button>
这当然行不通。
我意识到我必须:
- 将“TextBlock”从 xaml 传递到 ViewModelBase 中的方法参数。
- 在 C# 代码中的某处分配 GpioPin、GpioPinValue 和 PinNumber,并将它们传递给 ViewModelBase 内的方法。
为了填充该方法中的所有参数。 我真的不知道这是否是一个糟糕的 MVVM 设计,但我认为使用这种复杂模式的最好方法是将它分解成这样的小问题,看看它是否有价值。
【问题讨论】: