我想在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中的快捷方式,您可以编写propdp或dependencyProperty(根据您的版本)并按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的构造函数UserControl中MyControl.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)