【问题标题】:How to access/change the content of a button from ViewModel如何从 ViewModel 访问/更改按钮的内容
【发布时间】:2021-10-14 20:56:37
【问题描述】:

我希望根据按钮的内容从命令中执行某个功能。截至目前,我有两个按钮。 DesignImg 单击连接时,我需要将其更改为“断开连接”。如何从我的视图模型中访问按钮的内容。

这是我将连接/断开连接的视图模型:

namespace firstApp
{
    public class ViewModel
    {
        public TcpClient client = null;
        public ICommand MyCommand { get; set; }

        public ViewModel()
        {
            MyCommand = new Command(ExecuteMethod, canExecuteMethod);
        }

        private bool canExecuteMethod(object parameter)
        {
            return true;
        }

        public void ExecuteMethod(object parameter)
        {
            //if client is not connected do this... id client is connected then close client.
            try
            {
                // Create a TcpClient.
                // Note, for this client to work you need to have a TcpServer
                // connected to the same address as specified by the server, port
                // combination.
                Int32 port = 8000;
                TcpClient client = new TcpClient("127.0.0.1", port);

            }
            catch (ArgumentNullException ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
            catch (SocketException ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

这是我发送的视图模型:

namespace firstApp
{
    public class SendViewModel: ViewModel
    {
        public ICommand MySendCommand { get; set; }

        public SendViewModel()
        {
            MyCommand = new Command(ExecuteMethod, canExecuteMethod);
        }

        private bool canExecuteMethod(object parameter)
        {
            return true;
        }

        public void ExecuteSendMethod(object parameter)
        {
            if (client.Connected)
            {
                Byte[] data = System.Text.Encoding.ASCII.GetBytes("hello");

                // Get a client stream for reading and writing.
                //  Stream stream = client.GetStream();

                NetworkStream stream = client.GetStream();

                // Send the message to the connected TcpServer.
                stream.Write(data, 0, data.Length);
                //ChatScreentextBox.AppendText(TextToSend);//probably done need it here
                                                           //worker1.RunWorkerAsync();///gets to here
            }
            else
            {
                //ChatScreentextBox.AppendText("There is no connection");
            }
        }

【问题讨论】:

  • 只需在命令中使用 if 语句。并在您的 XAML 中设置样式触发器。样式触发器将更改按钮的文本,视图模型中的布尔值可以告诉您是否已连接。或者至少这是您可以获得所需结果的一种方式。
  • 如果 button.content = "Connect" 做这个功能?如果是这样,如果我在 viewModel 中,我如何访问该信息。我是 wpf 的新手,所以我可能会误解你的答案
  • 我在想你有一个类似于 IsConnected 的变量。当您单击按钮时,它会变为相反的。然后,您的按钮上有一个样式触发器,该触发器根据布尔值更改其名称。然后,您的命令只检查 bool 变量并根据它执行一个或另一个。

标签: c# wpf mvvm


【解决方案1】:

C#

//This variable needs to be usable in XAML fyi
private bool IsConnected = false;

// Your command method
private void ChangeConnectionStatus()
{
  if (IsConnected)
  {
    IsConnected = false;
    //call method for connecting bellow
  }
  else
  {
    IsConnected = true;
    //call method for disconnecting bellow
  }
}

XAML

                     <Button Command="{Binding ChangeConnectionStatus}">
                        <Button.Style>
                            <Style TargetType="Button">
                                <Style.Triggers>
                                    <DataTrigger Binding="{Binding IsConnected}" Value="true">
                                        <Setter Property="Content" Value="Conected" />
                                    </DataTrigger>
                                  <DataTrigger Binding="{Binding IsConnected}" Value="false">
                                        <Setter Property="Content" Value="Disconected" />
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </Button.Style>
                    </Button>

不可复制和粘贴代码,但应该让您知道如何操作。

同样在 ViewModel 中,人们通常会尽量避免编辑视图,这就是为什么 DataTrigger 通常是更好的方法,因为它将它们分开。

【讨论】:

    【解决方案2】:

    添加一个 ViewModel 属性并将其绑定到按钮文本。然后,您可以轻松地将按钮文本更改为其他内容。请注意,您的 ViewModel 需要实现 INotifyPropertyChanged 并添加适当的事件和事件引发方法。

    在 ViewModel 中(假设已实现 INotifyPropertyChanged):

    private string _connectButtonText = "Connect"; // set initial value here or in the constructor
    public string ConnectButtonText { get => _connectButtonText; set => { _connectButtonText = value; RaisePropertyChanged(nameof(ConnectButtonText)); }
    

    在 XAML 中(假设您页面的 DataContext 设置为您的 ViewModel):

    <Button Text={Binding ConnectButtonText} ... />
    

    要更改按钮文本,请在您的 ViewModel 中:

    public void ExecuteSendMethod(object parameter)
    {
        ...
    
        ConnectButtonText = "Disconnect";
    
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 1970-01-01
      • 1970-01-01
      • 2017-02-14
      • 1970-01-01
      • 1970-01-01
      • 2013-03-11
      相关资源
      最近更新 更多