【发布时间】: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 变量并根据它执行一个或另一个。