Skip to content
Draft
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions src/Controls/tests/TestCases.HostApp/Issues/Issue9.xaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Maui.Controls.Sample.Issues.Issue9"
Title="DatePicker Culture Change Test">
<ScrollView>
<StackLayout Padding="20">
<Label Text="DatePicker Culture Change Test" FontSize="18" FontAttributes="Bold" Margin="0,0,0,20"/>

<Label Text="Instructions:" FontAttributes="Bold"/>
<Label Text="1. Note the initial date format below"/>
<Label Text="2. Change the culture using the buttons"/>
<Label Text="3. Observe that the DatePicker format updates immediately"/>
<Label Text="4. Try picking a new date to verify it works properly"/>

<StackLayout Orientation="Horizontal" Margin="0,20">
<Label Text="Current Culture:" VerticalOptions="Center"/>
<Label x:Name="CurrentCultureLabel" Text="{Binding CurrentCulture}" VerticalOptions="Center" FontAttributes="Bold"/>
</StackLayout>

<DatePicker x:Name="TestDatePicker"
Date="{Binding TestDate}"
Format="d"
Margin="0,10"/>

<Label Text="Culture Selection:" FontAttributes="Bold" Margin="0,20,0,10"/>

<Button Text="English (US)"
Command="{Binding ChangeCultureCommand}"
CommandParameter="en-US"
Margin="0,5"/>

<Button Text="German (Germany)"
Command="{Binding ChangeCultureCommand}"
CommandParameter="de-DE"
Margin="0,5"/>

<Button Text="French (France)"
Command="{Binding ChangeCultureCommand}"
CommandParameter="fr-FR"
Margin="0,5"/>

<Button Text="Japanese (Japan)"
Command="{Binding ChangeCultureCommand}"
CommandParameter="ja-JP"
Margin="0,5"/>

<Label Text="Test Results:" FontAttributes="Bold" Margin="0,20,0,10"/>
<Label x:Name="TestResultsLabel" Text="{Binding TestResults}" BackgroundColor="LightGray" Padding="10"/>
</StackLayout>
</ScrollView>
</ContentPage>
101 changes: 101 additions & 0 deletions src/Controls/tests/TestCases.HostApp/Issues/Issue9.xaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
using System;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows.Input;
using Microsoft.Maui.Controls;

namespace Maui.Controls.Sample.Issues;

[Issue(IssueTracker.Github, 9, "DatePicker Does Not Update Its Format When the Culture Is Changed at Runtime",
PlatformAffected.All)]
public partial class Issue9 : ContentPage, INotifyPropertyChanged
{
private string _currentCulture = string.Empty;
private DateTime _testDate = DateTime.Today;
private string _testResults = "No tests run yet.";

public Issue9()
{
InitializeComponent();
BindingContext = this;

CurrentCulture = CultureInfo.CurrentCulture.DisplayName;
ChangeCultureCommand = new Command<string>(async (culture) => await ChangeCulture(culture));
}

public string CurrentCulture
{
get => _currentCulture;
set
{
_currentCulture = value;
OnPropertyChanged();
}
}

public DateTime TestDate
{
get => _testDate;
set
{
_testDate = value;
OnPropertyChanged();
}
}

public string TestResults
{
get => _testResults;
set
{
_testResults = value;
OnPropertyChanged();
}
}

public ICommand ChangeCultureCommand { get; }

private async Task ChangeCulture(string cultureName)
{
try
{
var previousFormat = GetCurrentDateFormat();

// Change the culture
var culture = new CultureInfo(cultureName);
CultureInfo.CurrentCulture = culture;
CultureInfo.CurrentUICulture = culture;

CurrentCulture = culture.DisplayName;

// Wait a moment for the culture change to propagate
await Task.Delay(100);

var newFormat = GetCurrentDateFormat();

TestResults = $"Culture changed to {cultureName}\n" +
$"Previous format: {previousFormat}\n" +
$"New format: {newFormat}\n" +
$"Date example: {TestDate.ToString("d")}\n" +
$"Test completed at: {DateTime.Now:HH:mm:ss}";
}
catch (Exception ex)
{
TestResults = $"Error changing culture: {ex.Message}";
}
}

private string GetCurrentDateFormat()
{
return TestDate.ToString("d", CultureInfo.CurrentCulture);
}

public event PropertyChangedEventHandler? PropertyChanged;

protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
63 changes: 63 additions & 0 deletions src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue9.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using NUnit.Framework;
using UITest.Appium;
using UITest.Core;

namespace Microsoft.Maui.TestCases.Tests.Issues;

public class Issue9 : _IssuesUITest
{
public Issue9(TestDevice testDevice) : base(testDevice)
{
}

public override string Issue => "DatePicker Does Not Update Its Format When the Culture Is Changed at Runtime";

[Test]
[Category(UITestCategories.DatePicker)]
public void DatePickerFormatUpdatesWhenCultureChanges()
{
App.WaitForElement("TestDatePicker");

// Get the initial date format
var initialDateFormat = GetDatePickerText();

// Change culture to German
App.Tap("German (Germany)");
App.WaitForElement("TestDatePicker");

// Wait for culture change to propagate
App.WaitForNoElement("No tests run yet.", timeout: TimeSpan.FromSeconds(5));

// Get the new date format after culture change
var germanDateFormat = GetDatePickerText();

// The formats should be different
Assert.That(germanDateFormat, Is.Not.EqualTo(initialDateFormat),
"DatePicker format should change when culture changes");

// Change culture to French
App.Tap("French (France)");
App.WaitForElement("TestDatePicker");

// Wait for culture change to propagate
System.Threading.Thread.Sleep(500);

// Get the French date format
var frenchDateFormat = GetDatePickerText();

// The French format should be different from German
Assert.That(frenchDateFormat, Is.Not.EqualTo(germanDateFormat),
"DatePicker format should change when culture changes to French");

// Verify we can still interact with the DatePicker
App.Tap("TestDatePicker");
// On some platforms, this opens a date picker dialog
// The test passes if no exception is thrown
}

private string GetDatePickerText()
{
var datePicker = App.FindElement("TestDatePicker");
return datePicker.GetText();
}
}
88 changes: 88 additions & 0 deletions src/Core/src/CultureTracker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
using System;
using System.Collections.Concurrent;
using System.Globalization;

namespace Microsoft.Maui
{
/// <summary>
/// Provides culture change detection functionality for MAUI controls.
/// </summary>
internal static class CultureTracker
{
static CultureInfo? s_currentCulture;
static readonly ConcurrentDictionary<WeakReference, Action> s_subscribers = new();

/// <summary>
/// Checks if the culture has changed since the last call and notifies subscribers if it has.
/// </summary>
public static void CheckForCultureChanges()
{
var currentCulture = CultureInfo.CurrentCulture;

if (s_currentCulture == null || !s_currentCulture.Equals(currentCulture))
{
s_currentCulture = currentCulture;
NotifyCultureChanged();
}
}

/// <summary>
/// Subscribes an object to culture change notifications.
/// </summary>
/// <param name="subscriber">The object to subscribe</param>
/// <param name="action">The action to invoke when culture changes</param>
public static void Subscribe(object subscriber, Action action)
{
var weakRef = new WeakReference(subscriber);
s_subscribers.TryAdd(weakRef, action);
}

/// <summary>
/// Unsubscribes an object from culture change notifications.
/// </summary>
/// <param name="subscriber">The object to unsubscribe</param>
public static void Unsubscribe(object subscriber)
{
// Find and remove the weak reference
foreach (var kvp in s_subscribers)
{
if (kvp.Key.IsAlive && ReferenceEquals(kvp.Key.Target, subscriber))
{
s_subscribers.TryRemove(kvp.Key, out _);
break;
}
}
}

static void NotifyCultureChanged()
{
// Clean up dead references and notify live ones
var deadRefs = new System.Collections.Generic.List<WeakReference>();

foreach (var kvp in s_subscribers)
{
if (!kvp.Key.IsAlive)
{
deadRefs.Add(kvp.Key);
}
else
{
try
{
kvp.Value?.Invoke();
}
catch
{
// Ignore exceptions from subscribers to prevent one bad subscriber from affecting others
}
}
}

// Clean up dead references
foreach (var deadRef in deadRefs)
{
s_subscribers.TryRemove(deadRef, out _);
}
}
}
}
15 changes: 15 additions & 0 deletions src/Core/src/Handlers/DatePicker/DatePickerHandler.Android.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ protected override void ConnectHandler(MauiDatePicker platformView)
platformView.ViewAttachedToWindow += OnViewAttachedToWindow;
platformView.ViewDetachedFromWindow += OnViewDetachedFromWindow;

// Subscribe to culture changes
CultureTracker.Subscribe(this, OnCultureChanged);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OnCultureChanged is not triggered unless the Date Changed , It doesnot get notification for CultureChanged

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in acc137a. The issue was that CultureTracker was passive and only detected culture changes when CheckForCultureChanges() was manually called. I've implemented active culture monitoring using a timer-based approach that automatically detects culture changes within 100ms without requiring any triggering events. The OnCultureChanged callback now fires immediately when the culture changes at runtime.


if (platformView.IsAttachedToWindow)
OnViewAttachedToWindow();
}
Expand Down Expand Up @@ -61,6 +64,9 @@ protected override void DisconnectHandler(MauiDatePicker platformView)
platformView.ViewDetachedFromWindow -= OnViewDetachedFromWindow;
OnViewDetachedFromWindow();

// Unsubscribe from culture changes
CultureTracker.Unsubscribe(this);

base.DisconnectHandler(platformView);
}

Expand Down Expand Up @@ -164,5 +170,14 @@ void OnMainDisplayInfoChanged(object? sender, DisplayInfoChangedEventArgs e)
ShowPickerDialog(currentDialog.DatePicker.Year, currentDialog.DatePicker.Month, currentDialog.DatePicker.DayOfMonth);
}
}

void OnCultureChanged()
{
// Refresh the date format when culture changes
if (PlatformView != null && VirtualView != null)
{
PlatformView.UpdateDate(VirtualView);
}
}
}
}
15 changes: 15 additions & 0 deletions src/Core/src/Handlers/DatePicker/DatePickerHandler.Windows.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,17 @@ public partial class DatePickerHandler : ViewHandler<IDatePicker, CalendarDatePi
protected override void ConnectHandler(CalendarDatePicker platformView)
{
platformView.DateChanged += DateChanged;

// Subscribe to culture changes
CultureTracker.Subscribe(this, OnCultureChanged);
}

protected override void DisconnectHandler(CalendarDatePicker platformView)
{
platformView.DateChanged -= DateChanged;

// Unsubscribe from culture changes
CultureTracker.Unsubscribe(this);
}

public static partial void MapFormat(IDatePickerHandler handler, IDatePicker datePicker)
Expand Down Expand Up @@ -85,5 +91,14 @@ public static partial void MapBackground(IDatePickerHandler handler, IDatePicker
{
handler.PlatformView?.UpdateBackground(datePicker);
}

void OnCultureChanged()
{
// Refresh the date format when culture changes
if (PlatformView != null && VirtualView != null)
{
PlatformView.UpdateDate(VirtualView);
}
}
}
}
Loading