【问题标题】:CaliburnMicro: In my calculator app, I'd like one method to handle all of the "number" buttons (0-9) with each button passing a different valueCaliburnMicro:在我的计算器应用程序中,我想要一种方法来处理所有“数字”按钮(0-9),每个按钮传递不同的值
【发布时间】:2020-11-29 11:13:02
【问题描述】:

目前,我的 calculator 上的每个按钮在 ShellViewmodel 中都有一个方法:

Shellview:

<Button x:Name="Btn1" Content="1"/>
<Button x:Name="Btn2" Content="2"/>
<Button x:Name="Btn3" Content="3"/>

ShellViewmodel:

private string _input = string.Empty;
public string Input
{
    get { return _input; }
    set
    {
        _input  = value;
        NotifyOfPropertyChange(() => Input);
    }
}

public void Btn1()
{
    Input += "1";
}
public void Btn2()
{
    Input += "2";
}
public void Btn3()
{
    Input += "3";
}

我意识到这是对我的计算器进行编程的一种幼稚方式,更好的解决方案是让每个按钮调用相同的方法并传递一个值(Btn1 将传递一个值 1,等等)。下面的代码不起作用;当我运行它并单击按钮时,什么也没有发生。因为我是初学者,所以我可能在装订方面犯了非常愚蠢的错误。将多个按钮绑定到一个方法的方法是什么,每个按钮都传递自己的值?谢谢。

Shellview:

<Button x:Name="Btn1" Command="{Binding NumberInput}" CommandParameter="1" Content="1"/>
<Button x:Name="Btn2" Command="{Binding NumberInput}" CommandParameter="2" Content="2"/>
<Button x:Name="Btn3" Command="{Binding NumberInput}" CommandParameter="3" Content="3"/>

ShellViewmodel:

private string _input = string.Empty;
public string Input
{
    get { return _input; }
    set
    {
            _display = value;
            NotifyOfPropertyChange(() => Display);
    }
}
public void NumberInput(string valuePassedFromButton)
{
    Input += valuePassedFromButton;
}

【问题讨论】:

    标签: c# wpf caliburn.micro


    【解决方案1】:

    内置的Command 属性应该绑定到ICommand 源属性。

    在 Caliburn.Micro 中,您可以使用 Message.Attach 属性将 Click 事件绑定到您的方法:

    <Button cal:Message.Attach="[Event Click] = [Action NumberInput('1')]" Content="1"/>
    <Button cal:Message.Attach="[Event Click] = [Action NumberInput('2')]" Content="2"/>
    <Button cal:Message.Attach="[Event Click] = [Action NumberInput('3')]" Content="3"/>
    

    【讨论】:

    • 谢谢,这很奏效。我需要在视图顶部添加一个命名空间引用(可能不是正确的术语):xmlns:cal="http://www.caliburnproject.org
    【解决方案2】:

    根据您的 XAML,它尝试绑定名为 NumberInput 的命令,作为默认的 WPF 命令绑定样式,不依赖于 Caliburn 的自动装配。但是,在您的 ViewModel 中,NumberInput 是 Method 的名称,而不是 ICommand

    我猜你必须将ICommand 的实现实例分配给DelegateCommand,如RelayCommandDelegateCommand,如非Caliburn 风格。

    • 例如,如果您实施了RelayCommandDelegateCommand
    ...
    public ICommand NumberInput{ get; private set;}
    ...
    
    public ShellViewModel{
           NumberInput=new RelayCommand<string>((valuePassedFromButton)=>{Input += valuePassedFromButton;});
    }
    ...
    

    【讨论】:

      猜你喜欢
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 2010-10-02
      • 1970-01-01
      相关资源
      最近更新 更多