c# - 具有可定制内容的 Windows 10 UWP UserControl

标签 c# uwp

我想在 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>

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

有什么办法吗?

最佳答案

为此,您需要在用户控件的代码隐藏中创建一个 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 键自动填充出整个属性的代码片段。

添加ContentPresenter

MyControl.xaml 中找到您要显示内容的位置,然后将 ContentPresenter 放在那里并绑定(bind)到 MainContent属性(property)。 有几种方法可以做到这一点。

x:Bind 语法的最新技术

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

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

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

使用与 DataContext 的绑定(bind) - 在 MyControl.xaml.cs 中的 UserControl 的构造函数中,您可以设置 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>

关于c# - 具有可定制内容的 Windows 10 UWP UserControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39313502/

相关文章:

.net - 为什么 MobileServiceSQLiteStore 数据库中的createdAt、deleted和updatedAt列为空?

c# - 属性更改时 UI 不更新

xaml - UWP 项目不支持触发器元素 (XAML)

c# - 为 .NET 中的类型自动生成的 GUID 是否一致?

C# 语法高亮着色

c# - MVVM Hierarchical Navigation 教程 StackOverFlow 异常

java - 使用 JNA 从 Java 调用 Windows UWP API

c# - 删除两个字符串之间的点

c# - 实际引用而不是复制 PtrToStructure?

c# - 我可以在 C# 的全局命名空间中隐藏类吗?