Không dùng được DateTime trong WPF

Em có dòng code WPF XAML thế này (phần behind-code em để code mặc định):

<Window x:Class="WpfApp1.MainWindow"
        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"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        xmlns:local="clr-namespace:WpfApp1"     
        mc:Ignorable="d"
        Title="Mega Program" Height="570" Width="570" Icon="{DynamicResource ImageSource1}" 
        Name="wnd">
    <Window.Background>
        <LinearGradientBrush>
            <GradientStop Offset="0" Color="White"/>
            <GradientStop Offset="1" Color="#FFCF682D"/>
        </LinearGradientBrush>
    </Window.Background>
    <Window.Resources>
        <BitmapImage x:Key="ImageSource1" CreateOptions="IgnoreImageCache" CacheOption="OnLoad" UriSource="C:\Users\Administrator\documents\visual studio 2017\Projects\WpfApp1\WpfApp1\Mega.png"/>
        
    </Window.Resources>
    <StackPanel Margin="10">
        <TextBlock Text="{Binding Source={x:Static system:DateTime.Now}, ConverterCulture='de-DE', StringFormat=German date: {0:D}}" />
        <TextBlock Text="{Binding Source={x:Static system:DateTime.Now}, ConverterCulture='en-US', StringFormat=American date: {0:D}}" />
        <TextBlock Text="{Binding Source={x:Static system:DateTime.Now}, ConverterCulture='ja-JP', StringFormat=Japanese date: {0:D}}" />
    </StackPanel>
</Window>

Em không hiểu sao mà nó cứ dính lỗi: WPF không hỗ trợ DateTime (DateTime is not supported in a Windows Presentation Foundation (WPF) project)
Mấy bác có thể giải đáp giúp em với ạ. Em cảm ơn.

Trên khai báo xmnls: sys sao dưới lại gọi system.
Hơn nữa cái system cũng chưa khai báo ở đâu cả.

Cách 1: Xác định DataContext của Window là sys.DateTime và binding đến Now.

<Window
    .....
    xmlns: sys="clr-namespace:System;assembly=mscorlib"
    .....
    >
    <Window.DataContext>
          <sys.DataTime/>
     </Window.DataContext>
     <Grid>
           <TextBlock Text="{Binding Now}"/>
      </Grid>
</Window>

Cách 2: Xác định một resource tương ứng với System.DateTime trong khu vực Resource của Window và binding đến Now qua x:StaticResource.

<Window
    ......
    xmnls: sys=...(nhu tren)
    .....
    <Window.Resource> 
        <sys.DateTime x:Key="SystemDateTime"/>
    </Window.Resource>
    <Grid>
          <TextBlock Text="{Binding Source={StaticResource SystemDateTime.Now}"/>
    </Grid>
</Window>
2 Likes

Em cảm ơn bác! Em kiến thức đang còn sơ sài quá.

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?