【问题标题】:Exposing child's property for binding暴露孩子的属性以进行绑定
【发布时间】:2014-09-06 23:21:17
【问题描述】:

假设我们有一个 CustomView,里面有 Entry(或任何其他视图):

public class CustomView : ContentView
{
    public CustomView()
    {
        var entry = new Entry();
        Content = entry;
    }
}

如何暴露条目的 Text 属性以使视图的 Text 属性可绑定?所以view的Text属性应该是双向绑定的,并且应该和entry的Text属性同步。

【问题讨论】:

    标签: xamarin.ios xamarin xamarin.forms


    【解决方案1】:

    您可以创建自己的 BindableProperties。在这种情况下,由于它是一个条目,因此请确保默认绑定模式为 2-way。然后你可以将Entry的BindingContext设置为当前对象,并将ContentView.Text绑定到Entry.TextProperty。

    public class CustomView : ContentView
    {
        public CustomView ()
        {
            var entry = new Entry ();
            entry.SetBinding (Entry.TextProperty, "Text");
            entry.BindingContext = this;
        }
    
        public static readonly BindableProperty TextProperty =
                BindableProperty.Create ("Text", typeof(string), typeof(CustomView), default(string), BindingMode.TwoWay);
    
        public string Text {
            get { return (string)GetValue (TextProperty); }
            set { SetValue (TextProperty, value); } 
        }
    }
    

    【讨论】:

    • 这是我首先尝试的。此解决方案有一个问题:每次您输入文本字段时,都会使该字段失去焦点(隐藏键盘)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    相关资源
    最近更新 更多