【问题标题】:split XAML children into multiple elements in a user control将 XAML 子项拆分为用户控件中的多个元素
【发布时间】:2016-09-13 12:10:56
【问题描述】:

我一直在尝试为问卷应用程序制作用户控件,在该应用程序中我有一些问题需要在特定条件下进行后续问题。一个简单的情景可能是,如果我们在某个问题上得到“是”,我们希望显示后续问题。

此时我已经按照Zenexer on a similar question 中的示例进行了操作。我的想法是,我会将我的用户控件的第一个孩子放在一个容器中(StackPanel 或其他),然后所有 第二个StackPanel 中的后续元素。但是在aforementioned example 中,所有子元素都被填充到用户控件中的一个元素中。据我了解,这是因为[ContentProperty(nameof(Children))] 设置为用户控件的所有内容。

我尝试在 Zenexer 的示例中更改 Children 的 getter 和 setter,但无济于事。

问题: 有没有办法使用 XAML 将我的用户控件的子级溢出到我的用户控件中的两个(或更多)元素中,如下所示:

MainWindow.xaml

<SubQuestionBox>
    <BinaryQuestion
            QuestionNumber="4.1"
            QuestionText="Parent question"/>

    <TextQuestion
            QuestionNumber="4.1.1"
            QuestionText="Child question 1"/>

    <TextQuestion
            QuestionNumber="4.1.2"
            QuestionText="Child question 2"/>
</SubQuestionBox>

SubQuestionBox.xaml

<UserControl x:Class="SubQuestionBox">

    <!--StackPanel To contain the question controls-->
    <StackPanel>
        <StackPanel x:Name="ParentContainer" />
        <StackPanel x:Name="SubQuestionsContainer" />
    </StackPanel>

</UserControl>

【问题讨论】:

  • 如果在您的 UI 中对问题的回答是肯定的,那么根据该属性的更改,您可以将数据绑定到另一个容器。阅读更多和 WPF 绑定和 MVVM,您应该能够使用这些知识构建您的逻辑。
  • @Versatile,这不是我要问的。我知道事件和数据绑定。问题是关于将用户控件的内容分配到两个包含元素中。
  • 我做了一个解决方法,我删除了“父问题”并将其插入到“父容器”中。我对我来说似乎不是很优雅,所以如果有人有更好的解决方案,请分享。

标签: c# wpf xaml


【解决方案1】:

如果有人想知道我是怎么做到的,它是这样的。

SubQuestionBox.xaml 类似于原始问题

SubQuestionBox.xaml.cs Children 属性是 DependencyProperty,就像在 the example of @Zenexer 中一样

public SubQuestionBox()
{
    InitializeComponent();
    Children = SubQuestionsContainer.Children;

    // add listener for Loaded event and call OnLoaded()     
    Loaded += OnLoaded; 
    if (ParentQuestion != null)
        // The BinaryQuestion has a AnswerChanged event
        ParentQuestion.AnswerChanged += ToggleCollapse;
}

public void DistributeQuestions()
{
    // This method seems super hacky to me. 
    // I would have thought there is a more elegant way

    UIElement parent = null;
    if (Children != null)
    {
        parent = Children[0];
        Children.RemoveAt(0);
    }
    if (ParentContainer != null && parent != null)
    {
        ParentContainer.Children.Add(parent);
    }

}

private void OnLoaded(object sender, RoutedEventArgs e)
{
    DistributeQuestions();
}

【讨论】:

  • 接受我自己的回答,因为没有其他建议。
猜你喜欢
  • 2011-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-30
相关资源
最近更新 更多