我正在向Windows应用商店编写应用程序,它将提供可以回答问题的练习。我创建了一个班级Question
,其中我有2个变量question
和answer
。
问题示例:
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中吗?
答案 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
}
}
}
}