我一直在尝试格式化数据网格中的字段数天.如何更改Period是访问的日期字段.在这次尝试中我不断收到错误:
‘{local:DateConverter}’值不是有效的MarkupExtension表达式.无法在名称空间’clr-namespace:Yabba’中解析’DateConverter’. ‘DateConverter’必须是MarkupExtension的子类.
然而,我所有的例子都显示了DateConverter:IValueConverter.
我只是想根据日期更改列以列出我想要的内容.但无法获得任何1个示例/方法.
XAML
<Window Name="MainForm" x:Class="Yabba.MainWindow" xmlns:local="clr-namespace:Yabba" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="655.217" Width="887.851" Loaded="Window_Loaded"> <Window.Resources> <local:DateConverter x:Key="dateConverter"/> </Window.Resources> <Grid> <DataGrid Name="dataGrid1" AutoGenerateColumns="False" PreviewKeyDown="dataGrid1_KeyDown" CanUserAddRows="false" SelectionUnit="FullRow" IsReadOnly="True" SelectionMode="Single" HorizontalAlignment="Left" VerticalAlignment="Top" Height="348" Width="753" SelectionChanged="dataGrid1_SelectionChanged" Margin="0,20,0" MouseDoubleClick="dataGrid1_MouseDoubleClick"> <DataGrid.Columns> <DataGridTextColumn Header="Question" Binding="{Binding title}"></DataGridTextColumn> <DataGridTextColumn Header="Period" Binding="{Binding started,Converter={local:DateConverter}}"></DataGridTextColumn> </DataGrid.Columns> </DataGrid> </Grid>
码
namespace Yabba { /// <summary> [ValueConversion(typeof(DateTime),typeof(String))] public class DateConverter : IValueConverter { public object Convert(object value,Type targetType,object parameter,CultureInfo culture) { DateTime date = (DateTime)value; return date.ToShortDateString(); } public object ConvertBack(object value,CultureInfo culture) { string strValue = value as string; DateTime resultDateTime; if (DateTime.TryParse(strValue,out resultDateTime)) { return resultDateTime; } return DependencyProperty.UnsetValue; } }
我在这做错了什么?
为使用此示例的任何人添加了注释:(无关联,请查看所选答案的答案)
您可能需要根据需要更改类型.
[ValueConversion(typeof(DateTime),typeof(String))]
我不得不改变我的
[ValueConversion(typeof(String),typeof(String))]
然后重铸到DateTime
DateTime date = DateTime.Parse((string)value);