c# - 分组相关的 ICommand

标签 c# wpf mvvm

我是 C# 新手,这是我的第一个 WPF 项目。我正在关注 this tutorial (使用他们的 RelayCommand 实现并尝试使用 MVVM。我正在实现标准 Windows 计算器的克隆。我想找到一种方法来对类似按钮的功能进行分组,因为我正在做的事情看起来很笨拙。

例如,这是我的三个按钮的 XAML

<Button Content="_7" Focusable ="False" Command="{Binding Seven}" Style="{DynamicResource NumberButton}" Margin="0,134,184,129"/>
<Button Content="_8" Focusable ="False" Command="{Binding Eight}" Style="{DynamicResource NumberButton}" Margin="46,134,138,129"/>
<Button Content="_9" Focusable ="False" Command="{Binding Nine}" Style="{DynamicResource NumberButton}" Margin="92,134,92,129"/>

这是用于这些的 ICommands:

public ICommand Nine { get { return new RelayCommand(NineExecute); } }
public ICommand Eight { get { return new RelayCommand(EightExecute); } }
public ICommand Seven { get { return new RelayCommand(SevenExecute); } }

和方法:

void NineExecute()
{
   NumberPressed("9");
}
void EightExecute()
{
   NumberPressed("8");
}
void SevenExecute()
{
   NumberPressed("7");
}

我应该调查什么以便将类似的功能按钮(例如数字)分组到一个 ICommand 中,使用一个可以确定发件人的方法 - 同时仍然不会像文章警告的那样将代码放在 Window 类中。

最佳答案

按钮的 Xlam 代码(假设您定义了数据上下文):

    <....DataContext>
        <loc:Commands/>
    </....DataContext>
    <Button Content="_9" 
            Command="{Binding Path=ShowMeABox}" 
            CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Content}"/>

我们的虚拟命令(使用提供的链接中的 RelayCommand<T>):

public class Commands
{
    private static readonly ICommand _showShowBoxCommand = 
        new RelayCommand<string>(str => MessageBox.Show(str));
    public static ICommand ShowMeABox { get { return _showShowBoxCommand; } }
}

就是这样。

仅供引用。

  1. 您似乎明确指定了按钮大小,这通常是一种不好的做法。要定位您的按钮,请使用堆栈或环绕面板,或网格/均匀网格。
  2. 阅读有关样式和模板的信息以提高代码重用率。

例子:

 <UniformGrid Columns="3" Rows="3">
    <UniformGrid.DataContext>
        <loc:Commands/>
    </UniformGrid.DataContext>
    <UniformGrid.Resources>
        <Style TargetType="Button">
            <Setter Property="Command" Value="{Binding ShowMeABox}"/>
            <Setter Property="CommandParameter" Value="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Content}"/>
        </Style>
    </UniformGrid.Resources>
    <Button Content="_1"/>
    <Button Content="_2"/>
    <Button Content="_3"/>
    <Button Content="_4"/>
    <Button Content="_5"/>
    <Button Content="_6"/>
    <Button Content="_7"/>
    <Button Content="_8"/>
    <Button Content="_9"/>
</UniformGrid>
  1. 也许可以绑定(bind)Enumerable.Range(0,10)以 MVVM 方式自动填充控件。

祝你好运!

关于c# - 分组相关的 ICommand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16115004/

相关文章:

c# - 可以接受在点之前有空格吗?

c# - Task.Delay 是如何工作的?

c# - 以最低键值获取键值对的最便宜方法?

wpf - VS2017 : An Error Occured while finding the resource dictionary

c# - Wpf Datagrid将选定值与值路径绑定(bind)

wpf - 将高 DPI 图像转换为低 DPI 进行打印抛出 OutOfMemoryException

c# - wpf 复选框列表不更新

wpf - 使用 PRISM 和 MVVM 的 ViewModel 的参数化构造函数

c# - 将对象传递给 View 模型

wpf - 资源字典定位器