有可能使一个WPF用户控件和子/ UserControls或不?
是的,这是可能的。也许,短样本会有帮助。
父控制(XAML):
<UserControl x:Class="WpfApplication4.CustomMenu"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<ItemsControl ItemsSource="{Binding Items, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"/>
</Grid>
</UserControl>
父控制(代码隐藏):
public partial class CustomMenu : UserControl
{
public CustomMenu()
{
InitializeComponent();
}
public ObservableCollection<CustomMenuItem> Items
{
get { return (ObservableCollection<CustomMenuItem>)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register(
"Items",
typeof(ObservableCollection<CustomMenuItem>),
typeof(CustomMenu),
new PropertyMetadata(new ObservableCollection<CustomMenuItem>()));
}
儿童控制(XAML):
<UserControl x:Class="WpfApplication4.CustomMenuItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<TextBlock Text="Hello, world!"/>
</Grid>
</UserControl>
用法:
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication4"
Title="MainWindow" Height="350" Width="525">
<Grid>
<local:CustomMenu>
<local:CustomMenu.Items>
<local:CustomMenuItem />
<local:CustomMenuItem />
<local:CustomMenuItem />
</local:CustomMenu.Items>
</local:CustomMenu>
</Grid>
</Window>
但目前还不清楚,你想达到什么目的。也许,你需要一个custom control,从HeaderedItemsControl继承?
非常感谢这个例子。我想要实现的是创建一个菜单和它的菜单子项(我已经做了这个控制)。我要检查是否最好使用自定义控件而不是用户控件。再次感谢。我将以这种方式实施它或使用CustomControl建议。 – CodingMate
我注意到了一个奇怪的行为,如果我在另一个'Window'或'Page'中拥有另一个'UserControl'的实例,它将累积第一个菜单的项目,在第二个菜单中。例如:如果我在家中有一个菜单,而在另一个页面中有另一个菜单,则当我打开主页时,它将显示完美,但是如果我打开另一页,则会在第一页旁边显示菜单项通过第二页菜单的项目。 – CodingMate