我想在 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.xaml
和 MyControl.xaml.cs
中定义。
创建MainContent
依赖属性
在 UserControl.xaml.cs
的 UserControl
类定义中添加以下内容:
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 中的快捷方式,您可以编写 propdp
或 dependencyProperty
(取决于您的版本)并按 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/