2010-02-08 16 views
2

幾年前,我做了很多WPF,但似乎忘記了一切。將簡單的業務類綁定到WPF UserControl

假設我有一個簡單的商務課程,比如TFS工作項目。

public class WorkItem 
{ 
    public WorkItem(string name, DateTime date) 
    { 
     Name = name; 
     Date = date; 
    } 

    public string Name { get; set; } 
    public DateTime Date { get; set; } 
} 

然後我有一個WorkItems的列表,可能是這樣的。

class WiList : ObservableCollection<WorkItem> 
{ 
    public WiList() : base() 
    { 
     Add(new WorkItem("1", DateTime.Now)); 
     Add(new WorkItem("2", DateTime.Now)); 
    } 
} 

然後我有一個UserControl代表一個WorkItem,就像這樣。

<UserControl 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" 
    x:Class="WrapPanelItemsControlTest.WorkItemControl" 
    x:Name="UserControl" 
    d:DesignWidth="640" d:DesignHeight="480" HorizontalAlignment="Left" 
    VerticalAlignment="Top" Width="72" Height="40"> 

<StackPanel x:Name="LayoutRoot"> 
    <TextBlock x:Name="Name"/> 
    <TextBlock x:Name="Date"/> 
</StackPanel> 

主窗口包含一個WrapPanel來保存用戶控件。我的問題是,我如何創建一個綁定到WiList並顯示WorkItems的WrapPanel?我記得之前做過這樣的事情,但對於我的死亡我不記得是怎麼回事(可能來自Bea Costa的博客)。當然,我無法在任何地方找到我的舊測試代碼,並且在搜索示例時看起來很糟糕。

任何幫助appreaciated。

回答

0

首先,您需要將WiList類的實例綁定到ItemsControl的ItemsSource,然後爲您的WorkItem應用DataTemplate。

還有一個類似的線程here

你可以找到更多關於ItemsControl的ItemsPanel here

2

您可能需要使用ItemsControlWrapPanel可用作集合元素的佈局面板。如果您只需要UserControl即可顯示一個對象的屬性,那麼更好的選擇是使用DataTemplate。下面是一些XAML:

<Window.Resources> 

    <DataTemplate x:Key="WorkItemTemplate" DataType="{x:Type local:WorkItem}"> 
     <StackPanel> 
      <TextBlock Text="{Binding Name}"/> 
      <TextBlock Text="{Binding Date}"/> 
     </StackPanel> 
    </DataTemplate> 

</Window.Resources> 

<Grid> 

    <ItemsControl 
     x:Name="itemsList" 
     ItemTemplate="{StaticResource WorkItemTemplate}" 
     > 
     <ItemsControl.ItemsPanel> 
      <ItemsPanelTemplate> 
       <WrapPanel /> 
      </ItemsPanelTemplate> 
     </ItemsControl.ItemsPanel> 
    </ItemsControl> 

</Grid> 

而在後臺代碼綁定ItemsControl到集合:

itemsList.ItemsSource = new WIList(); // or wherever the collection comes from 

附:初始化ItemsSource並且通常從代碼隱藏訪問控件以將它們綁定到數據不是一種好的做法。您需要一個ViewModel(Presenter)類作爲窗口的DataContext。如果您考慮與WPF保持一段時間,我的建議是 - 嘗試使用MVVM

P.P.S.如果您需要WPF跟上屬性值的更改,請不要忘記在WorkItem上執行INotifyPropertyChanged

+0

正在初始化ItemsSource _from code-behind_不是一個好習慣。你可能意思是這樣,但從P.S.中可能不清楚。 +1 =) – 2010-02-08 21:08:53

+0

謝謝!當然,我放棄了這些話,我會糾正自己 – arconaut 2010-02-08 21:15:33