gpt4 book ai didi

c# - 如何使用 WPF 将十进制值作为命令参数传递给命令?

转载 作者:行者123 更新时间:2023-11-30 15:16:14 24 4
gpt4 key购买 nike

我有一个在 Prism 6 框架之上使用 C# 和 WPF 编写的应用程序。

我正在尝试使用 XAMl 创建一个按钮,单击时,我想将一个固定的十进制值传递给我的 View 模型。

<Button Content="5"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Command="{Binding ProcessAmount}"
CommandParameter="5.00000"
FontSize="24"
Height="75"
Width="85" />

在我的 View 模型中,我有以下内容

public class ViewModel : BindableBase
{
public DelegateCommand<decimal?> ProcessAmount { get; set; }

public ViewModel()
{
ProcessAmount = new DelegateCommand<decimal?>(HandleProcessAmount, CanProcessAmount);
}

private bool CanProcessAmount(decimal? amount)
{
return amount.HasValue && amount.Value != 0;
}

private void HandleProcessAmount(decimal? amount)
{
// do something with the amount
}
}

但是当我编译应用程序时,我在 XAML View 中收到错误 Specified cast is not valid.

如何从 View 中发送固定的十进制值?

最佳答案

在 Xaml 世界中,每个数字都被视为 Double。您需要手动转换/转换,否则可能会出现意外情况。这意味着,在您的 View 模型中,将数字检索为 double? 而不是 decimal?,然后适本地将其转换/转换为 decimal。例如:

public class ViewModel : BindableBase
{
public DelegateCommand<double?> ProcessAmount { get; set; }

public ViewModel()
{
ProcessAmount = new DelegateCommand<double?>(HandleProcessAmount, CanProcessAmount);
}

private bool CanProcessAmount(double? amount)
{
return amount.HasValue && amount.Value != 0;
}

private void HandleProcessAmount(double? amount)
{
decimal amountInDecimal = Convert.ToDecimal(amount.Value); // convert it to decimal

// do something with the amount
}
}

这样做的好处是,对double 类型的数字进行计算比对decimal 类型的数字进行计算更容易。但是,我想这不是您想要的。

您的问题的解决方案 是在 xaml 中将类型明确指定为 Decimal。您需要导入 System mscorlib,然后将 SystemDecimal 分配给 CommandParameter

xmlns:s="clr-namespace:System;assembly=mscorlib"

<Button Content="5"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Command="{Binding ProcessAmount}"
FontSize="24"
Height="75"
Width="85">
<Button.CommandParameter>
<s:Decimal>5.00000</s:Decimal>
</Button.CommandParameter>
</Button>

这消除了在 VM 端转换数字类型的必要。

关于c# - 如何使用 WPF 将十进制值作为命令参数传递给命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50244170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com