c# - 如何通过在另一个窗口中单击的按钮更改标签的内容?
问题描述
这是我做过的第一件与 C# 有关的事情,但我过去学过 lua 和 python。当一些朋友过来时,我想制作一个宾果游戏应用程序,我想我会试一试。基本上我有 2 个窗口,1 个用于宾果游戏呼叫者,一个可以显示在屏幕上供玩家查看。宾果调用者窗口具有所有控件,但我希望能够更改播放器窗口上的内容。我有一个按钮,当我单击它时,我希望它显示图像并更改一些文字,上面写着“我们有赢家”。但是我找不到在不同窗口中更改内容的方法:(
这是我的代码以及一些图片。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
Window window = new Window1();
private void Button_Click(object sender, RoutedEventArgs e)
{
window.Show();
PlayBingo.Visibility = Visibility.Hidden;
DeclareWinner.Visibility = Visibility.Visible;
RollNumber.Visibility = Visibility.Visible;
}
private void Declare_Winner(object sender, RoutedEventArgs e)
{
}
private void Roll_Number(object sender, RoutedEventArgs e)
{
}
}
编辑
public string BingoNumberChange(string bingonumber)
{
BingoNo.Content = bingonumber;
return bingonumber;
}
我在我的 window1 脚本中创建了这个函数。但是我不能从 MainWindow 脚本调用它???
解决方案
在 Window1 类中创建一个接受新文本并从主窗口调用此方法的公共方法。您可以使用接口对多个窗口类执行此操作
public class Window1 : Window
{
// skip all other code
public void SetLabelText(string str)
{
label1.Content= str;
}
}
从 MainWindow 按钮单击调用此方法
Window1 newWindowobj = new Window1():
newWindowobj.SetLabel("new text");
newWindowobj.Show();
另一种方法
IContentUpdatable.cs
public interface IContentUpdatable
{
void UpdateContent(string content);
}
Window1 代码
public partial class Window1 : Window, IContentUpdatable
{
public Window1()
{
InitializeComponent();
}
public void UpdateContent(string content)
{
lblCaption.Content = content;
}
}
主窗口代码
Window1 window1 = new Window1();
private void btnClick_Click(object sender, RoutedEventArgs e)
{
((IContentUpdatable)window1).UpdateContent("Passed from Main Window");
window1.Show();
}
推荐阅读
- reactjs - Strapi:在反应时触发其他组件
- python - Python - 将小时数转换为日期?
- git - 在 .gitconfig 键中使用非 ASCII 字符是否可行?
- java - 关闭选项卡时返回特定选项卡 - JavaFx
- kubernetes - 将 Kubernetes pod 的日志发送到 Splunk
- algorithm - 查找一组线段中的所有交点?
- pandas - 如何使用 Python 从组合的出现中形成计数矩阵?
- macos - Mac上的docker,在任何目录上安装卷失败“安装被拒绝:EOF”
- python - Python 中的快速数据集增强 - 深度学习
- javascript - 如何使用 jspdf-Autotable 在表格中添加自定义最后一行