Home > Blockchain >  How to access/change the content of a button from ViewModel
How to access/change the content of a button from ViewModel

Time:10-15

I want a certain function to execute from a command depending on the content of the button. As of now I have two buttons.DesignImg When connect is clicked I need to change it to "Disconnect". How do I access the content of the button from my view model. Here is my viewModel where I will connect/ disconnect

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());
        }
    }

And here is the view model of my send.

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");
        }
    }

CodePudding user response:

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>

Not copy and passable code but should give you and Idea of how to do it.

Also in the ViewModel usually people try to avoid editing the view that's why the DataTrigger is generally a better way because it keeps them separated.

CodePudding user response:

Add a ViewModel property and bind it to the button text. Then you can change the button text to something else easily. Note that your ViewModel will need to implement INotifyPropertyChanged and add the appropriate event and event-raising method.

In ViewModel (assumes INotifyPropertyChanged is implemented):

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

In XAML (assumes your page's DataContext is set to your ViewModel):

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

To change the button text, in your ViewModel:

public void ExecuteSendMethod(object parameter)
{
    ...

    ConnectButtonText = "Disconnect";

    ...
}
  • Related