2013-04-12 58 views
2

具體控制我有一個包含不同類型的對象的列表:特定數據類型

List<object> myList = new List<object>(); 
    DateTime date = DateTime.Now; 
    myList.Add(date); 
    int digit = 50; 
    myList.Add(digit); 
    myList.Add("Hello World"); 
    var person = new Person() { Name = "Name", LastName = "Last Name", Age = 18 }; 
    list.ItemsSource = myList; 

    public class Person 
    { 
     public string Name { get; set; } 
     public string LastName { get; set; } 
     public int Age { get; set; } 
    } 

我希望看到他們在ListBox與不同類型的控件。例如:DatePickerDateTimeTextBlockstringTextBoxPerson的名字和姓氏...

是否有可能做XAML這個任務?

幫助讚賞。

+0

是的,這是可能的,使用DataTemplateSelector:http://tech.pro/tutorial/807/wpf-tutorial-how-to-use-a-datatemplateselector –

+0

@FlorianGI這是完全不需要的,並涉及不必要的代碼。 –

回答

3
<Window x:Class="MiscSamples.DataTemplates" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:sys="clr-namespace:System;assembly=mscorlib" 
     Title="DataTemplates" 
     Height="300" 
     Width="300"> 
    <Window.Resources> 

    <!-- DataTemplate for strings --> 
    <DataTemplate DataType="{x:Type sys:String}"> 
     <TextBox Text="{Binding Path=.}" /> 
    </DataTemplate> 

    <!-- DataTemplate for DateTimes --> 
    <DataTemplate DataType="{x:Type sys:DateTime}"> 
     <DataTemplate.Resources> 
     <DataTemplate DataType="{x:Type sys:String}"> 
      <TextBlock Text="{Binding Path=.}" /> 
     </DataTemplate> 
     </DataTemplate.Resources> 
     <DatePicker SelectedDate="{Binding Path=.}" /> 
    </DataTemplate> 


    <!-- DataTemplate for Int32 --> 
    <DataTemplate DataType="{x:Type sys:Int32}"> 
     <Slider Maximum="100" 
       Minimum="0" 
       Value="{Binding Path=.}" 
       Width="100" /> 
    </DataTemplate> 
    </Window.Resources> 
    <ListBox ItemsSource="{Binding}" /> 
</Window> 

代碼背後:

public partial class DataTemplates : Window 
    { 
     public DataTemplates() 
     { 
      InitializeComponent(); 

      var myList = new List<object>(); 
      myList.Add(DateTime.Now); 
      myList.Add(50); 
      myList.Add("Hello World"); 

      DataContext = myList; 
     } 
    } 

結果:

enter image description here

正如你所看到的,有一個在所有沒有理由使用代碼來操縱WPF UI元素(除了一些非常特殊的情況)

編輯:

注意,你通常不會創建一個類的DataTemplate命名空間System內(如System.String。這只是給你一個例子。如果你真的需要這個,你可能需要爲每種類型創建一個ViewModel

+0

沒想過這個,非常好的解決方案。 ;) –

+0

是的,它的工作原理。我發現了一個小問題。我把這三個DataTemplates放入ListBox.Resources。現在如果你打開一個DatePicker,所有的日期都在TextBoxes中。我可以只爲這個ListBox說這個DataTemplate嗎? – Dilshod

+0

@Dilshod看我的編輯。這應該解決它。 –