如何在WPF中将接口类型IEnumerable集合绑定到自定义控件
实现方案
核心思路是用WPF的ItemsControl控件做集合数据的模板化渲染,按以下步骤调整即可:
1. 调整后台代码
WPF绑定只支持公共属性,不支持字段,首先需要把你声明的enumSlots从字段改为属性,如果后续需要动态增删集合元素时UI自动同步,建议替换为ObservableCollection<ISlot>:
// 替换原来的字段声明,改为公共属性 public ObservableCollection<ISlot> EnumSlots { get; set; } // 构造函数里的赋值逻辑调整 public MainWindow() { InitializeComponent(); // 用GetSlots()的返回值初始化可观察集合 EnumSlots = new ObservableCollection<ISlot>(GetSlots()); DataContext = this; }
如果不需要动态变更集合内容,直接把IEnumerable字段包一层公共属性也可以:
public IEnumerable<ISlot> EnumSlots => enumSlots;
2. 给自定义控件添加绑定支持
自定义控件要支持外部绑定传值,需要定义依赖属性,在CustomControlSlot.cs中添加以下代码:
// Number依赖属性 public static readonly DependencyProperty NumberProperty = DependencyProperty.Register( nameof(Number), typeof(int), typeof(CustomControlSlot), new PropertyMetadata(default(int))); public int Number { get => (int)GetValue(NumberProperty); set => SetValue(NumberProperty, value); } // Name依赖属性 public static readonly DependencyProperty NameProperty = DependencyProperty.Register( nameof(Name), typeof(string), typeof(CustomControlSlot), new PropertyMetadata(default(string))); public string Name { get => (string)GetValue(NameProperty); set => SetValue(NameProperty, value); }
然后修改CustomControlSlot的样式模板,把内部两个Label用TemplateBinding绑定到上面的依赖属性:
<!-- 以下代码放在CustomControlSlot的ControlTemplate内 --> <StackPanel> <Label Content="{TemplateBinding Number}" /> <Label Content="{TemplateBinding Name}" /> </StackPanel>
3. MainWindow界面添加集合渲染控件
在MainWindow的XAML中加入ItemsControl,绑定你的集合,指定每个项的渲染模板为自定义控件即可:
<!-- 注意把下面的local替换为你自己项目中ISlot、CustomControlSlot所在的命名空间前缀 --> <ItemsControl ItemsSource="{Binding EnumSlots}"> <!-- 可选:修改ItemsPanel调整排列方式,默认是垂直排列的StackPanel --> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <WrapPanel /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <!-- 每个集合项的渲染模板 --> <ItemsControl.ItemTemplate> <DataTemplate DataType="{x:Type local:ISlot}"> <local:CustomControlSlot Number="{Binding Number}" Name="{Binding Name}" Margin="5" /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl>
内容的提问来源于stack exchange,提问作者SideSky
相关产品推荐
相关产品推荐

