2013-01-17 45 views
0

我有一個對象,我正在通過我的用戶控件作爲屬性。然後循環訪問對象屬性,並根據訂單日期在不同的選項卡上在運行時創建控件。 請通過附加的圖像以便更好地理解。使用WPF中的DataBinding創建動態控件

它的工作正常,但這是如此WINFORM類型,是否有可能在運行時使用WPF綁定,依賴項屬性或類似的東西創建控件。

enter image description here

enter image description here

感謝

回答

0

是它在某種程度上可以創建使用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 :

   <CheckBox Grid.Column="0" IsChecked="{Binding IsActive}" Content="{Binding Name}"/> 
       <TextBox Grid.Column="1" Text="{Binding DateTime}"/> 
      </Grid> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox>