现在有这么一个需求,需要动态添加自定义控件到界面,自定义控件数量不固定,内容是通过服务获取的,以前是做winform的,winform简单,直接 new自定义控件添加上去就行,现在wpf mvvm模式,不知道怎么做了,能否在viewmodel中添加一个 observablecollection,界面绑定这个属性,界面自动生成这么多个自定义控件?如果可以,各位大佬能否提供下实现思路,有个demo什 么的最好了。
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication5
{
///
/// MainWindow.xaml 的交互逻辑
///
public partial class MainWindow : Window
{
public MainWindowViewModel user { get; set; }
public MainWindow()
{
InitializeComponent();
user = new MainWindowViewModel();
mygrid.DataContext = user;//指定ViewModel
}
}
}
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace WpfApplication5
{
public class MainWindowViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public MainWindowViewModel()
{
Btns = new ObservableCollection
}
private ObservableCollection
public ObservableCollection
{
get { return btns; }
set { btns = value; }
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApplication5
{
public class Item : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
}
}
}
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local ="clr-namespace:WpfApp1"
Title="MainWindow" Height="450" Width="800">
using System.Collections.ObjectModel;
using System.Windows;
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Items = new ObservableCollection
另外,数据模板的强处,在于它可以利用数据类型,来决定具体的展示模板。还小蜜蜂论坛发帖机可以这么用