i have created a custom control by overriding textbox. in that control I have modified the resources collection, but it is not reflecting in the UI that is loaded earlier. Hence need to apply some logic to reapply the theme changes.
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using System.Collections.Generic;
namespace Sample
{
public sealed class CustomTextBox : TextBox
{
public CustomTextBox()
{
this.DefaultStyleKey = typeof(TextBox);
}
#region IsMandatory
public static readonly DependencyProperty IsMandatoryProperty = DependencyProperty.Register(nameof(IsMandatory), typeof(bool), typeof(CustomTextBox), new PropertyMetadata(false, OnIsMandatoryPropertyChanged));
public bool IsMandatory
{
get { return (bool)GetValue(IsMandatoryProperty); }
set { SetValue(IsMandatoryProperty, value); }
}
private static void OnIsMandatoryPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.OldValue != e.NewValue)
{
var control = d as CustomTextBox;
bool isUpdated;
if (control.IsMandatory)
{
isUpdated = control.Resources.AddOrUpdate("TextControlHeaderForeground", "Red");
}
else
{
isUpdated = control.Resources.AddOrUpdate("TextControlHeaderForeground", control.Resources.GetValueOrDefault("SystemControlForegroundBaseHighBrush"));
}
if (isUpdated)
{
control.UpdateTheme();
}
}
}
#endregion
public void UpdateTheme()
{
// need to update the UI to reflect the changes made in resources
}
}
public static class Extensions
{
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key)
{
return dict.TryGetValue(key, out var value) ? value : default(TValue);
}
public static bool AddOrUpdate<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
if (dictionary.ContainsKey(key))
{
if (!dictionary[key].Equals(value))
{
dictionary[key] = value;
return true;
}
}
else
{
dictionary.Add(key, value);
return true;
}
return false;
}
}
}