【问题标题】:How to add arbitrary content within a user control如何在用户控件中添加任意内容
【发布时间】:2014-01-10 13:41:14
【问题描述】:

我有一个 Windows Phone 应用程序,我想在其中实现以下目标: 定义一个(用户)控件,它有一个 Button 和一个任意控件。用户单击按钮后,第二个控件将变为可见,而按钮将隐藏。 我可以直接在 CodeBehind 或 ViewModel 中实现这一点,但我希望有某种控制,我可以在需要它的所有地方重复使用。

我在 Google 上搜索了一下,然后遇到了 ContentPresenter。 控制:

<StackPanel Background="Red" x:Name="LayoutRoot">
    <Button Content="Dummy"/>
    <ContentPresenter/>
</StackPanel>

XAML 调用:

<controls:MyControl>
   <TextBlock Text="Text Content"/>
</controls:MyControl>

但是 Contentpresenter 不能这样使用,并且永远不会显示 Button,因为内容的页面 XAML 定义将覆盖用户控件 xaml 中定义的内容。

然后我找到了使用模板的提示,但我还不明白如何将它与我想在此处应用的逻辑结合起来。

我是否应该创建一个 userControl,它具有 Button 的 VisibilityProperties 和模板使用的其他控件?

欢迎任何建议或提示,以了解在哪里继续我的搜索。

【问题讨论】:

  • 创建一个自定义控件,如下所示:geekchamp.com/articles/creating-a-wp7-custom-control-in-7-steps。将您的 Container、显示/隐藏按钮和 ContentPresenter 放入控件模板中。然后,您可以在任何地方使用此 MyControl 控件,使用自定义内容模板设置 Content Presenter(如文章中所示)

标签: c# xaml windows-phone-8 windows-store-apps


【解决方案1】:

怎么样:

控制:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="auto"/>
    </Grid.RowDefinitions>
    <Button Content="ClickMe" Click="Button_Click"/>
    <StackPanel Grid.Row="1" x:FieldModifier="public" x:Name="Content"/>
</Grid>

Control.cs:

private void Button_Click(object sender, RoutedEventArgs e)
    {
        if (Content.Visibility == Visibility.Collapsed)
        {
            Content.Visibility = Visibility.Visible;
        }
        else
        {
            Content.Visibility = Visibility.Collapsed;
        }
    }

MainPage.xaml:

<local:MyUserControl1 x:Name="MyControl" HorizontalAlignment="Left" Margin="327,124,0,0" VerticalAlignment="Top"/>

MainPage.xaml.cs(添加内容):

MyControl.Content.Children.Add(new Button());
        MyControl.Content.Children.Add(new Button());
        MyControl.Content.Children.Add(new Button());
        MyControl.Content.Children.Add(new Button());
        MyControl.Content.Children.Add(new Button());
        MyControl.Content.Children.Add(new Button());

【讨论】:

  • 这只是一个快速的方法
  • 这里的问题是,您将名称为“Content”的 Stackpanel 放入控件中。我想在 MainPage.xaml 中将此作为我的控件的内容,而无论在 Mainpage.xaml 中添加什么内容,该按钮都应由控件添加。
猜你喜欢
  • 2012-06-24
  • 2011-02-11
  • 2019-03-22
  • 1970-01-01
  • 2017-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多