带有可自定义内容的Windows 10 UWP UserControl

Ami*_*min 5 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>
Run Code Online (Sandbox Code Playgroud)

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

有没有办法做到这一点?

Mar*_*und 13

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

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

创建MainContent依赖项属性

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

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 ); }
}
Run Code Online (Sandbox Code Playgroud)

作为Visual Studio中的快捷方式,您可以编写propdpdependencyProperty(根据您的版本)并按Tab键自动填写整个属性的代码段.

添加 ContentPresenter

在里面MyControl.xaml找到你想要显示内容的地方,并在ContentPresenter那里放置一个绑定到MainContent属性.有几种方法可以做到这一点.

最新的x:Bind语法技巧

<ContentPresenter Content="{x:Bind MainContent}" />
Run Code Online (Sandbox Code Playgroud)

使用绑定元素 - 在这里你需要为元素本身添加一个x:Name属性,例如UserControl调用它RootControl,然后像这样创建绑定:

<ContentPresenter Content="{Binding MainContent, ElementName=RootControl}" />
Run Code Online (Sandbox Code Playgroud)

使用绑定DataContext - 在in的构造函数UserControlMyControl.xaml.cs你可以设置DataContext- this.DataContext = this;然后简单地写:

<ContentPresenter Content="{Binding MainContent}" />
Run Code Online (Sandbox Code Playgroud)

用法

现在你UserControl准备好了,你可以像这样使用它:

<local:MyControl>
  <local:MyControl.MainContent>
     <!-- some content :-) -->
     <Image Source="Assets/LockScreenLogo.png" Width="100"/>
  </local:MyControl.MainContent>
</local:MyControl>
Run Code Online (Sandbox Code Playgroud)

  • 很好,我建议使用第二种方式绑定MainContent(和任何其他属性),因此使用时,内部元素将保留其定义的DataContext,否则MyControl将成为其DataContext (2认同)