【问题标题】:Windows 10 UWP UserControl with customizable content具有可自定义内容的 Windows 10 UWP UserControl
【发布时间】:2017-02-16 19:06:44
【问题描述】:

我想在 Windows 10 UWP 中制作一个内容不断变化的用户控件。

我知道如何制作一个简单的用户控件,但我需要一个这样的用户控件:

<Controls:UserControl x:Name="Usercontrol1" Margin="0,10,0,0" Grid.Row="1">
    <Controls:UserControl.MainContent>
        <Grid x:Name="Content">
            //Items are here
        </Grid>
    </Controls:UserControl.MainContent>
</Controls:UserControl>

我的用户控件中有 Grid,它是空的,我想在每个页面中为该网格提供不同的项目。我想要一种在页面中为我的用户控件设置网格的方法,然后将此网格添加到我的用户控件而不是那个空网格。

有什么办法吗?

【问题讨论】:

    标签: c# uwp


    【解决方案1】:

    为此,您需要在用户控件的代码隐藏中创建一个MainContent 依赖属性并使用ContentPresenter 显示它。

    假设您的用户控件在MyControl.xamlMyControl.xaml.cs 中定义。

    创建MainContent 依赖属性

    UserControl.xaml.csUserControl 类定义中添加以下内容:

    public static readonly DependencyProperty MainContentProperty =
       DependencyProperty.Register( 
          "MainContent", 
          typeof( object ), 
          typeof( MyControl ), 
          new PropertyMetadata( default( object ) ) );
    
    public object MainContent
    {
        get { return ( object ) GetValue( MainContentProperty ); }
        set { SetValue( MainContentProperty, value ); }
    }
    

    作为 Visual Studio 中的快捷方式,您可以编写 propdpdependencyProperty(取决于您的版本)并按 Tab 键自动填写整个属性的代码 sn-p .

    添加ContentPresenter

    MyControl.xaml 中找到要显示内容的位置,并在其中放置一个ContentPresenter,并绑定到MainContent 属性。 有几种方法可以做到这一点。

    x:Bind 语法的最新技术

    <ContentPresenter Content="{x:Bind MainContent}" />
    

    使用元素绑定 - 在这里,您需要将 x:Name 属性添加到 UserControl 元素本身,例如将其命名为 RootControl,然后像这样创建绑定:

    <ContentPresenter Content="{Binding MainContent, ElementName=RootControl}" />
    

    使用与DataContext的绑定 - 在MyControl.xaml.csUserControl 的构造函数中,您可以设置DataContext - this.DataContext = this;,然后简单地写:

    <ContentPresenter Content="{Binding MainContent}" />
    

    用法

    现在您的UserControl 已准备就绪,您可以像这样使用它:

    <local:MyControl>
      <local:MyControl.MainContent>
         <!-- some content :-) -->
         <Image Source="Assets/LockScreenLogo.png" Width="100"/>
      </local:MyControl.MainContent>
    </local:MyControl>
    

    【讨论】:

    • 它有效,但我有一个问题。我在用户控件的 mycontnet 中的项目无法单击或选择。我该如何解决?
    • 很好,我推荐使用第二种方式绑定MainContent(以及其他任何属性),这样使用时,内部元素将保持其定义的DataContext,否则MyControl将成为它们的DataContext跨度>
    • 但是我怎样才能在 UserControl MainContent 中进行 ElementName 绑定工作?示例:&lt;TextBlock Text="{Binding Text, Mode=OneWay, ElementName=OuterTextBlock}"/&gt;
    猜你喜欢
    • 1970-01-01
    • 2011-10-11
    • 2018-07-16
    • 2019-07-23
    • 2016-07-25
    • 2016-12-28
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多