在字符串之间插入TextBox

时间:2014-06-14 13:43:21

标签: c# string textbox windows-store-apps windows-8.1

我正在向Windows应用商店编写应用程序,它将提供可以回答问题的练习。我创建了一个班级Question,其中我有2个变量questionanswer

问题示例:

Question q = new Question(
    "This is simple [1] of question. This is the [2]",
    new string[]
    {
        "sample",
        "end"
    });

我想要的是将问题作为TextBlock添加到网格视图中,并在TextBox的地方添加问题[1](我们将在哪里写下答案)和[2]。所以它看起来像这样:

<TextBox>
     <TextBlock> This is simple </TextBlock>
<TextBox/>

<TextBlock> of question. This is the </TextBlock><TextBox/>

我不确定我是否应该这样做。我可以在Question类中创建一个方法,以我呈现的方式将项目添加到MainPage.xaml中吗?

1 个答案:

答案 0 :(得分:0)

我认为你应该让自己UserControl来展示问题。关键是在后面的代码中动态创建控件(TextBlock / TextBox),并将它们作为子项添加到WrapPanel。我不能在这里看到简单的XAML决定。

XAML:

<UserControl <!--skipped--> >
    <WrapPanel x:Name="mainPanel">
    </WrapPanel>
</UserControl>

代码背后:

partial class QuestionControl : UserControl
{
    public QuestionControl()
    {
        InitializeComponent();
    }

    private Question _question = null;
    public Question Question
    {
        get { return _question; }
        set
        {
            _question = value;
            UpdateUI();
        }
    }

    private void UpdateUI()
    {
        mainPanel.Children.Clear();

        if (this.Question != null)
        {
            List<FrameworkElement> controls = new List<FrameworkElement>();
            string[] questionSegments = // some code to split question here

            foreach (var qs in questionSegments)
            {
                controls.Add(new TextBlock() { Text = qs } );
            }

            for (int i = 0; i < this.Question.AnswerStrings.Length; i++)
            {
                string answer = this.Question.AnswerStrings[i];
                TextBox newTextBox = new TextBox();
                controls.Insert(i * 2 + 1, newTextBox); // inserting TextBoxes between TextBlocks
            }

            foreach (var control in controls)
            {
                mainPanel.Children.Add(control); // adding all the controls to the wrap panel
            }
        }
    }
}