[英]How do I define two bindable properties which update each other in Xamarin.Forms?
[英]How to bind values between two bindable properties in composite control Xamarin Forms?
我創建了一個從Frame擴展的Forms控件,左側有一個Editor和一個box視圖。 而且我公開了Frame的Text屬性,以便可以在XAML綁定中使用。 如果我綁定來自xaml的文本的值,它將顯示在編輯器中。 但是如何在不更改屬性的情況下將用戶編輯文本設置回“框架文本屬性”呢?
public class MyEditor : Frame
{
public static readonly BindableProperty TextProperty = BindableProperty.Create("Text", typeof(string), typeof(MyEditor), String.Empty);
public string Text
{
get { return (string)this.GetValue(TextProperty); }
set
{
this.SetValue(TextProperty, value);
// this set is not calling when used from XAML Bindings
if (this.editor != null)
this.editor.Text = value;
}
}
private Editor editor;
private BoxView leftView;
private StackLayout contentHolder;
public MyEditor()
{
this.HasShadow = false;
this.Padding = 0;
this.IsClippedToBounds = true;
contentHolder = new StackLayout()
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
Orientation = StackOrientation.Horizontal,
Spacing = 0
};
this.Content = contentHolder;
editor = new Editor();
editor.TextChanged += editor_TextChanged;
editor.HorizontalOptions = LayoutOptions.FillAndExpand;
editor.VerticalOptions = LayoutOptions.FillAndExpand;
leftView = new BoxView()
{
IsVisible = false,
WidthRequest = 5,
BackgroundColor = Color.FromHex("ff9900")
};
contentHolder.Children.Add(leftView);
contentHolder.Children.Add(editor);
}
void editor_TextChanged(object sender, TextChangedEventArgs e)
{
// how to update user edited text back to (Text)TextProperty without triggering OnPropertyChanged ?
//Text = editor.text;
// this triggers the Property change again.
}
protected override void OnPropertyChanged(string propertyName = null)
{
base.OnPropertyChanged(propertyName);
//update the Text property of MyEditor to actual editor
if (propertyName == TextProperty.PropertyName)
{
editor.Text = Text;
}
}
}
Xaml代碼:
<CustomControl:MyEditor x:Name="cEditor" Text="{Binding Text}" WidthRequest="300" HeightRequest="150"/>
在代碼中,您可以在可綁定屬性的設置器中以及在OnPropertyChanged功能中設置編輯器的文本,還可以在OnTextChanged事件中設置框架的文本-3條代碼。
相反,所有這些都嘗試通過雙向綁定將這兩個文本綁定在一起,如下所示:
public MyEditor()
{
...
editor.SetBinding(Editor.TextPropety, new Binding("Text", BindingMode.TwoWay,source:this));
}
同樣,在您的Xaml代碼中,將綁定模式更改為雙向綁定,以反映綁定上下文中的文本更改。 實際上,我認為,如果您更改Xaml,它將解決您當前的問題(“將用戶編輯文本設置回Frame Text屬性”),但是imho綁定這兩個文本會更加優雅。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.