Jus*_*ier 5 c# wpf user-controls wpf-controls
我知道如何在WPF中创建自定义用户控件,但是如何才能使某人能够提供ItemTemplate?
我有一个用户控件,它是几个其他WPF控件的混合,其中一个是ListBox.我想让控件的用户指定列表框的内容,但我不知道如何传递该信息.
编辑:接受的答案适用于以下更正:
<UserControl x:Class="WpfApplication6.MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:WpfApplication6">
<ListBox ItemTemplate="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type src:MyControl}}, Path=ItemsSource}" />
</UserControl>
Run Code Online (Sandbox Code Playgroud)
Tod*_*ite 15
您将需要向控件添加DependencyProperty.如果从UserControl或Control派生,则xaml看起来会略有不同.
public partial class MyControl : UserControl
{
public MyControl()
{
InitializeComponent();
}
public static readonly DependencyProperty ItemTemplateProperty =
DependencyProperty.Register("ItemTemplate", typeof(DataTemplate), typeof(MyControl), new UIPropertyMetadata(null));
public DataTemplate ItemTemplate
{
get { return (DataTemplate) GetValue(ItemTemplateProperty); }
set { SetValue(ItemTemplateProperty, value); }
}
}
Run Code Online (Sandbox Code Playgroud)
这是用于UserControl的xaml.
<UserControl x:Class="WpfApplication6.MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:WpfApplication6">
<ListBox ItemTemplate="{Binding ItemTemplate, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type src:MyControl}}}" />
</UserControl>
Run Code Online (Sandbox Code Playgroud)
这是控件的xaml:
<Style TargetType="{x:Type src:MyControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type src:MyControl}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ListBox ItemTemplate="{TemplateBinding ItemTemplate}" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10642 次 |
| 最近记录: |