【问题标题】:Edit the content of a text block in a list C# (WPF Application)在列表 C#(WPF 应用程序)中编辑文本块的内容
【发布时间】:2018-11-29 19:42:46
【问题描述】:

所以我有五个文本块添加到一个列表中,每个文本块都应该有自己的 1 到 6 之间的随机数。

我知道我可以为每个文本块 (int randomNumberOne, randomNumberTwo, etc) 做一个新的 int,但我想看看我是否可以弄清楚如何为每个循环制作一个列表和一个。

有没有办法在列表中编辑文本框的内容?如果有,我还没有找到任何方法。

这是我目前的代码。

List<TextBlock> randomBoxList = new List<TextBlock>();

        public MainWindow()
        {
            InitializeComponent();
            randomBoxList.Add(randomBoxOne);
            randomBoxList.Add(randomBoxTwo);
            randomBoxList.Add(randomBoxThree);
            randomBoxList.Add(randomBoxFour);
            randomBoxList.Add(randomBoxFive);
        }

    Random randomGenerator = new Random();
    int randomNumber;

    private void randomButton_Click(object sender, RoutedEventArgs e)
    {
        foreach (TextBlock textBlock in randomBoxList)
        {
            randomNumber = randomGenerator.Next(1, 7);
            //Code to change randomBox content goes here. 
        }
    }

【问题讨论】:

  • wpf 还是 wnforms?
  • WPF。抱歉,我会编辑我的帖子以说明这一点。
  • 我为此推荐 MVVM。然后你可以将它绑定到 ContentControl 并循环遍历一个列表。
  • 我将要提出的建议。如果您将按钮定义为循环容器类型的元素(如列表等),这可能会有点工作
  • 虽然使用 MVVM 绝对是一个不错的建议,但您也可以这样做 textBlock.Text = randomNumber.ToString()

标签: c# wpf list random textblock


【解决方案1】:

如果这是 WPF,你应该可以像这样使用 textBlock.Text 属性:

 public partial class MainWindow : Window
{
    List<System.Windows.Controls.TextBlock> randomBoxList = new List<System.Windows.Controls.TextBlock>();

    public MainWindow()
    {
        InitializeComponent();
        randomBoxList.Add(randomBoxOne);
        randomBoxList.Add(randomBoxTwo);
        randomBoxList.Add(randomBoxThree);
        randomBoxList.Add(randomBoxFour);
        randomBoxList.Add(randomBoxFive);
    }

    Random randomGenerator = new Random();
    int randomNumber;

    private void randomButton_Click(object sender, RoutedEventArgs e)
    {
        foreach (System.Windows.Controls.TextBlock textBlock in randomBoxList)
        {
            randomNumber = randomGenerator.Next(1, 7);
            textBlock.Text = randomNumber.ToString();
        }
    }
}

【讨论】:

  • 不知道这是你能做的事情。我想有办法做到这一点,但我无法为我的生活弄明白。一定不是看得太辛苦。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2012-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-25
  • 1970-01-01
  • 1970-01-01
  • 2013-02-19
相关资源
最近更新 更多