[英]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.