I want to change the border color of a TextBox
to use it in Xamarin.Forms. This is done via a custom renderer.
First try:
Custom renderer:
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
var control = this.Control as TextBox;
if (control != null)
{
control.BorderBrush = new SolidColorBrush(Windows.UI.ColorHelper.FromArgb(0, 8, 38, 85));
}
}
Result: the border color is gone and it changes to my color after I click into the TextBox
Second try:
Custom renderer (subclass from EntryRenderer
):
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
if(this.Control == null)
{
var control = new ColoredTextBox();
SetNativeControl(control);
}
base.OnElementChanged(e);
}
Custom control:
public class ColoredTextBox : FormsTextBox
{
protected override void OnGotFocus(RoutedEventArgs e)
{
base.OnGotFocus(e);
var control = e.OriginalSource as TextBox;
control.BorderBrush = new SolidColorBrush(Windows.UI.ColorHelper.FromArgb(0, 88, 128, 85));
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
var control = e.OriginalSource as TextBox;
control.BorderBrush = new SolidColorBrush(Windows.UI.ColorHelper.FromArgb(0, 88, 128, 85));
}
}
Result: app crashes with
Exception: Object reference not set to an instance of an object.
StackTrace (last line): at Xamarin.Forms.Platform.UWP.VisualElementRenderer`2.SetNativeControl(TNativeElement control)
Third try:
Custom renderer changed to ViewRenderer
:
public class CustomEntryRenderer : ViewRenderer<CustomEntry, ColoredTextBox>
{
protected override void OnElementChanged(ElementChangedEventArgs<CustomEntry> e)
{
var view = Element as CustomEntry;
if (e.OldElement != null || view == null)
return;
var textBox = new ColoredTextBox();
SetNativeControl(textBox);
base.OnElementChanged(e);
}
}
Result: the border color is gone and it changes to my color after I click into the TextBox
. Furthermore the text I set in XAML is not set on the new control (but thats no surprise). Now the OnGotFocus()
and OnLostFocus()
events are called, but as written before they do not bring the desired effect. Interestingly, the events are called all the time if I set a breakpoint and it doesn't stop calling.
How can I programmatically change the border color of a TextBox
in UWP?
Edit:
Regarding the duplicate: The linked question targets the accent color in general, but refers to the TextBox
as example. Mainly my goal was to do it programmatically and NOT by style/theme. Since there currently seems no other way to do it, the solution is nearly the same. So I'll leave it up to the community do decide if it is a duplicate or not.
TargetType='TextBox'
in the App.xaml of the UWP project? How should this work together? Can you improve your selected answer? – testing