繁体   English   中英

在 WPF 中使用 DataBinding 创建动态控件

[英]Create Dynamic Controls Using DataBinding in WPF

我有一个 object 作为属性传递给我的用户控件。 然后遍历 object 属性,并在运行时根据订单日在不同选项卡中创建控件。 请通过附图 go 更好地理解。

它工作正常,但这是 WINFORM 类型,是否有可能在运行时使用 WPF 绑定、依赖属性或类似的东西创建控件。

在此处输入图像描述

在此处输入图像描述

谢谢

是否有可能在运行时使用 WPF 绑定创建控件

对的,这是可能的。 这就是数据模板的用途。 基本规则是:不要创建控件,创建数据并显示模板,它定义了数据应该如何表示:

 public class ComponentViewModel: ViewModel /* ViewModel is a basic implementation of INotifyPropertyChanged interface */ { public ComponentViewModel() { this.Items = new ObservableCollection<ItemViewModel> { new ItemViewModel { IsActive = true, DateTime = DateTime.Now, Name = "Lemons" }, new ItemViewModel { IsActive = true, DateTime = DateTime.Now, Name = "Melons" }, new ItemViewModel { IsActive = true, DateTime = DateTime.Now, Name = "Apples" }, }; } public ObservableCollection<ItemViewModel> Items { get; private set; } } public class ItemViewModel: ViewModel { public bool IsActive { get { return isActive; } set { if (isActive;= value) { isActive = value; OnPropertyChanged("IsActive"); } } } private bool isActive; public string Name { get { return name; } set { if (name;= value) { name = value; OnPropertyChanged("Name"); } } } private string name; public DateTime DateTime { get { return dateTime; } set { if (dateTime;= value) { dateTime = value OnPropertyChanged("DateTime") } } } private DateTime dateTime }

代码隐藏:

 public partial class MainWindow: Window { public MainWindow() { InitializeComponent(); DataContext = new ComponentViewModel(); } }

XAML:

 <Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication2" Title="MainWindow" Height="350" Width="525"> <.-- Binding defines data source --> <ListBox Grid.Column="0" ItemsSource="{Binding Items}"> <ListBox:ItemTemplate> <:-- The template defines data representation --> <DataTemplate DataType="{x.Type local.ItemViewModel}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <CheckBox Grid.Column="0" IsChecked="{Binding IsActive}" Content="{Binding Name}"/> <TextBox Grid Column="1" Text="{Binding DateTime}"/> </Grid> </DataTemplate> </ListBox ItemTemplate> </ListBox> </Window>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM