Specific control for a specific DataType

前端 未结 1 1616
长发绾君心
长发绾君心 2020-12-20 02:56

I have a List which contains different types of objects:

    List myList = new List();
    DateTime date = DateTime.Now;
    myLi         


        
                      
相关标签:
1条回答
  • 2020-12-20 03:08
    <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>
    

    Code Behind:

     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;
            }
        }
    

    Result:

    enter image description here

    As you can see, there's no reason at all to use code to manipulate UI elements in WPF (except some very very specific cases)

    Edit:

    Note that you don't usually create a DataTemplate for classes inside the System namespace (such as System.String. This is only to give you an example. If you really needed this you would probably have to create a ViewModel for each type.

    0 讨论(0)
提交回复
热议问题