【发布时间】:2017-02-14 03:00:44
【问题描述】:
我想更改 TextBox 的边框颜色以在 Xamarin.Forms 中使用它。这是通过自定义渲染器完成的。
第一次尝试:
自定义渲染器:
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));
}
}
结果:边框颜色消失,点击TextBox后变为我的颜色
第二次尝试:
自定义渲染器(EntryRenderer 的子类):
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
if(this.Control == null)
{
var control = new ColoredTextBox();
SetNativeControl(control);
}
base.OnElementChanged(e);
}
自定义控件:
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));
}
}
结果:应用程序崩溃
异常:对象引用未设置为对象的实例。
StackTrace(最后一行):在 Xamarin.Forms.Platform.UWP.VisualElementRenderer` 2.SetNativeControl(TNativeElement控件)
第三次尝试:
自定义渲染器更改为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);
}
}
结果:边框颜色消失了,当我点击TextBox 后它变成了我的颜色。此外,我在 XAML 中设置的文本没有设置在新控件上(但这并不奇怪)。现在调用了OnGotFocus() 和OnLostFocus() 事件,但正如之前所写的那样,它们并没有带来预期的效果。有趣的是,如果我设置断点并且它不会停止调用,则事件会一直被调用。
如何在 UWP 中以编程方式更改 TextBox 的边框颜色?
编辑:
关于重复:链接的问题通常以强调色为目标,但以TextBox 为例。主要是我的目标是以编程方式而不是按样式/主题来完成。由于目前似乎没有其他方法可以做到这一点,因此解决方案几乎相同。所以我会让社区决定它是否是重复的。
【问题讨论】:
-
我想改变代码中的颜色,这样我以后可以实现一个属性。所以我根本不应该使用自定义渲染器?我应该在 UWP 项目的 App.xaml 中使用
TargetType='TextBox'设置样式吗?这应该如何协同工作?你能改进你选择的答案吗?
标签: xamarin textbox xamarin.forms uwp windows-10-universal