[英]Passing data from custom renderer to custom control
我的项目中有以下Xamarin.Forms
控件:
public partial class AutoCompleteView : Xamarin.Forms.View
{
public event EventHandler<TextChangedEventArgs> TextChanged;
public static readonly BindableProperty TextProperty = BindableProperty.Create(
propertyName: "Text",
returnType: typeof(string),
declaringType: typeof(string),
defaultBindingMode: BindingMode.TwoWay);
public static readonly BindableProperty SuggestionsProperty = BindableProperty.Create(
propertyName: "Suggestions",
returnType: typeof(IEnumerable<string>),
declaringType: typeof(ObservableCollection<string>),
defaultBindingMode: BindingMode.OneWay);
public IEnumerable<string> Suggestions
{
get => (IEnumerable<string>)GetValue(SuggestionsProperty);
set => SetValue(SuggestionsProperty, value);
}
public string Text
{
get => (string)GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
public AutoCompleteView () : base()
{
InitializeComponent ();
}
private void OnTextChanged(TextChangedEventArgs e)
{
TextChanged?.Invoke(this, e);
}
}
以及以下自定义Android渲染器:
public class AutoCompleteViewRenderer : Xamarin.Forms.Platform.Android.ViewRenderer<AutoCompleteView, AutoCompleteTextView>
{
public AutoCompleteViewRenderer(Context context) : base(context) { }
protected override void OnElementChanged(ElementChangedEventArgs<AutoCompleteView> e)
{
base.OnElementChanged(e);
if (e.OldElement != null || this.Element == null)
return;
var autoComplete = new AutoCompleteTextView(this.Context);
SetNativeControl(autoComplete);
this.Control.SetSingleLine();
this.Control.SetTextColor(Android.Graphics.Color.Black);
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (this.Element == null || this.Control == null)
return;
var autoComplete = (AutoCompleteView)sender;
this.Control.Text = autoComplete.Text;
if (autoComplete.Suggestions != null)
{
var suggestions = autoComplete.Suggestions.ToArray();
this.Control.Adapter = new ArrayAdapter<string>(Context, Resource.Layout.autoCompleteCell, suggestions);
}
}
}
问题在于控件无法从渲染器接收文本(即,既不调用Text
setter,也不调用绑定模型的setter)。 我怎么解决这个问题?
谢谢mjwills,我在这里发现了逻辑错误。 显然, this.Control.Text = autoComplete.Text
应该反转(即autoComplete.Text = this.Control.Text
),因为this.Control
是本机控件,它将文本更改传递给自定义AutoCompleteView
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.