在WPF中创建类似UserControl的ComboBox,可以通过以下步骤实现:
<UserControl x:Class="WpfApp1.MyUserControl"
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"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<TextBlock Text="{Binding Name}" FontSize="16" FontWeight="Bold"/>
<TextBlock Text="{Binding Description}" Margin="0,20,0,0"/>
</Grid>
</UserControl>
SelectedItem="{Binding SelectedItem}"
ItemTemplate="{StaticResource MyUserControlTemplate}">
public class MyItem
{
public string Name { get; set; }
public string Description { get; set; }
}
public class MainViewModel : INotifyPropertyChanged
{
public ObservableCollection<MyItem> Items { get; set; }
= new ObservableCollection<MyItem>
{
new MyItem { Name = "Item 1", Description = "This is item 1" },
new MyItem { Name = "Item 2", Description = "This is item 2" },
new MyItem { Name = "Item 3", Description = "This is item 3" }
};
public MyItem SelectedItem { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
var template = new DataTemplate();
template.DataType = typeof(MyItem);
template.VisualTree = new FrameworkElementFactory(typeof(MyUserControl));
template.Seal();
Resources.Add("MyUserControlTemplate", template);
}
}
这样,ComboBox中的每个Item都将使用自定义的UserControl来显示,实现了类似UserControl的效果。
领取专属 10元无门槛券
手把手带您无忧上云