我在iOS和UWP中尝试使用格式=“ D”的Xamarin Forms DatePicker。
在iOS中,星期几显示在DatePicker中,类似于
2016年4月24日,星期日
但是在UWP中,DatePicker不显示星期几,而是显示:
2016年4月24日
所以,我的问题是:
如何在UWP的DatePicker中显示星期几?
这是我用xaml编写的代码:
<DatePicker WidthRequest="350" HeightRequest="30" Margin="20,0,0,200" x:Name="DtPicker" Format="D" />
答案 0 :(得分:0)
首先,我想谈一谈Format = "D"
。在文档The Long Date ("D") Format Specifier中,这是一个字符串值。但是无法在DatePicker中显示。
DateTime date1 = new DateTime(2008, 4, 10);
Console.WriteLine(date1.ToString("D",
CultureInfo.CreateSpecificCulture("en-US")));
// Displays Thursday, April 10, 2008
Console.WriteLine(date1.ToString("D",
CultureInfo.CreateSpecificCulture("pt-BR")));
// Displays quinta-feira, 10 de abril de 2008
Console.WriteLine(date1.ToString("D",
CultureInfo.CreateSpecificCulture("es-MX")));
// Displays jueves, 10 de abril de 2008
现在,您可以查看UWP中设计的 DatePicker ,它无法显示星期几。
因此,唯一的方法是自定义DatePicker。
在Xamarin Forms中,使用 Custom Renderers 可以在UWP中自定义DatePciker
。
在表单中创建自定义DatePicker :
public class CustomDatePicker : DatePicker
{
}
在 Xaml 中使用它:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:App8"
mc:Ignorable="d"
x:Class="App8.MainPage">
<StackLayout Padding="100">
<!-- Place new controls here -->
<Label Text="Welcome to Xamarin.Forms!"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" />
<local:CustomDatePicker />
</StackLayout>
</ContentPage>
然后在UWP中,创建自定义渲染器类:
[assembly: ExportRenderer(typeof(CustomDatePicker), typeof(CustomDatePickerRenderer))]
namespace App8.UWP
{
public class CustomDatePickerRenderer : DatePickerRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<DatePicker> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.Background = new SolidColorBrush(Colors.Cyan);
var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("dayofweek");
DateTime dateToFormat = DateTime.Now;
var mydate = formatter.Format(dateToFormat);
Control.Header = mydate;
Control.DateChanged += Control_DateChanged;
}
}
private void Control_DateChanged(object sender, Windows.UI.Xaml.Controls.DatePickerValueChangedEventArgs e)
{
//throw new NotImplementedException();
var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("month day dayofweek year");
DateTime dateToFormat = e.NewDate.DateTime;
var mydate = formatter.Format(dateToFormat);
Control.Header = mydate;
}
}
}
注意:这里我只是在
Header
的{{1}}中设置星期几,因为没有找到修改Picker UI的方法。我认为,如果继续研究document,将需要更多时间来寻找最佳解决方案。
当前显示效果为如下: