【发布时间】:2015-11-25 09:10:19
【问题描述】:
我创建了一个从 Frame 扩展的 Forms 控件,左侧有一个编辑器和一个框视图。我公开了 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"/>
【问题讨论】:
标签: c# xaml xamarin xamarin.forms