![](/img/trans.png)
[英]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.