Date Converter using WPF

后端 未结 2 1391
闹比i
闹比i 2020-12-18 06:59
public class DateTimeConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, Sy         


        
相关标签:
2条回答
  • 2020-12-18 07:35

    You dont need a converter for doing this. You can use the StringFormat in binding itself to format your selected datetime to show just date in mm/dd/yyyy format.

    <TextBlock Text="{Binding Date, StringFormat={}{0:MM/dd/yyyy}}" />
    

    I tested with this code and it is working fine. XAML:

    <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding TestList}">
                <DataGrid.Columns>
                <DataGridTemplateColumn Header="Start">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Start, StringFormat=d}" FontFamily="Verdana" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
                <DataGridTemplateColumn.CellEditingTemplate>
                    <DataTemplate>
                        <DatePicker SelectedDate="{Binding Start}" FontFamily="Verdana"  >
                            <DatePicker.CalendarStyle>
                                <Style TargetType="Calendar">
                                    <Setter Property="DisplayMode" Value="Month"/>
                                </Style>
                            </DatePicker.CalendarStyle>
                        </DatePicker>
                    </DataTemplate>
                </DataGridTemplateColumn.CellEditingTemplate>
            </DataGridTemplateColumn>
                </DataGrid.Columns>
            </DataGrid>
    

    Model:

        public class TestData
        {
            DateTime start;
            public DateTime Start
            {
                get { return start; }
                set { start = value; }
            }
    
        }
    

    ViewModel has list of TestData to be bound to DataGrid:

    public List<TestData> TestList { get; set; }
    
    0 讨论(0)
  • 2020-12-18 07:48

    Try this.

    DateTime test = (DateTime) value ;
    string date = test.Date.ToString("d/M/yyyy"); 
    //Use test.Date.tostring instad of test.tostring(...)
    return (date);
    
    0 讨论(0)
提交回复
热议问题