首页 > 解决方案 > MVVMLight C# 如何更改按钮内容

问题描述

我是使用 MVVMLight 的 WPF 新手,并且正在努力掌握事情的工作原理。我在 xaml 中有一个按钮:

<Button x:Name="button" Content="Button" 
    HorizontalAlignment="Left" 
    Margin="29,374,0,0" 
    VerticalAlignment="Top" Width="75" 
    Command="{Binding BeginCollectionCommand}"/>

并让视图模型响应按钮按下。 BeginCollectionCommand = new RelayCommand(BeginCollectionCommandExecute, () => true);

我未能找到我的问题的答案

视图模型代码将按钮绑定“BeginCollectionCommand”定义为

public RelayCommand BeginCollectionCommand { get; set; }
    public MainWindowViewModel()
  {
    BeginCollectionCommand = new RelayCommand(BeginCollectionCommandExecute, () => true);
    //at this point i believe is where i set the button content to "working..."
    //and disable.
  }

  public void BeginCollectionCommandExecute()
  {
    /// do my working class code

    //I think at this point I want to set the code to change button content to
    //enable, conent to "done" then wait and set to "start"
  }

有人可以帮忙吗?

标签: c#wpfmvvm-light

解决方案


你的问题可以总结为三种问题。

  1. 如何启用或禁用按钮。
  2. 如何更改按钮的内容。
  3. 如何在一段时间后更改内容。

对于第一个和第二个问题,将您的按钮绑定IsEnable到 viewModel 中的属性并将内容绑定到字符串

在 xml 中。

<Button x:Name="button" 
    Content="{Binding ButtonString}"
    HorizontalAlignment="Left" 
    Margin="29,374,0,0" 
    VerticalAlignment="Top" Width="75"
    IsEnabled="{Binding ButtonEnabled}"
    Command="{Binding BeginCollectionCommand}"/>

在视图模型中

    // Set true or button cannot be pressed.
    bool m_Enabled = true;
    public bool ButtonEnabled
    {
        get{  return m_Enalbed; }
        set{ m_Enabled = value; 
         // RaisePropertyChanged MUST fire the same case-sensitive name of property
             RaisePropertyChanged( "ButtonEnabled" );
           }
        }
    }

    public bool ButtonString
    {
     get;set;
    }
    bool m_String = false;
    public bool ButtonString
    {
        get{  return m_String; }
        set{ m_String = value; 
             // RaisePropertyChanged MUST fire the same case-sensitive name of property
             RaisePropertyChanged( "ButtonString" );
           }
        }
    }


public void BeginCollectionCommandExecute()
{
    //I simplify the way of variable passing, 
    //You need to take care of how to set property from command to viewmodel. 
    //A method delegate would be okay.
    ButtonEnabled = false;
    ButtonString = "Working";
    // working here
    ButtonEnabled = true;
    ButtonString = "Done";
}

对于第三个问题,您可以使用计时器或 ThreadSleep 即可。


推荐阅读