Xamarin访问其他视图中条目

2w3rbyxf  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(105)

我正在通过Xamarin开发多平台应用程序。
我在单独的视图中使用自定义条目,并且在应用程序的某些页面中使用
这是我的简单密码

<ContentView
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="prova.MyView">

<ContentView.Content>

    <Entry x:Name="MyEntry"
           TextChanged="MyEntry_TextChanged"
           Margin="100"/>

</ContentView.Content>

和cs文件

public partial class MyView : ContentView
{
    public MyView()
    {
        InitializeComponent();
    }

    void MyEntry_TextChanged(System.Object sender, Xamarin.Forms.TextChangedEventArgs e)
    {
    }
}

在我的页面中,我插入了一个简单的代码

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="prova.MainPage"
         xmlns:pages="clr-namespace:prova">

<StackLayout>

    <pages:MyView/>

</StackLayout>

我想知道当在我的ContentPage中触发MyEntry_TextChanged时,我如何获得?一种解决方案是使用MessaggingCenter,但我想知道是否有更好、更优雅的解决方案

pokxtpni

pokxtpni1#

我能想到两种方法。

1.继承自Entry类别,如Jason所述。

public class MyView : Entry
{
    public MyView()
    {
        InitializeComponent();
    }
}

这将公开可绑定的TextChanged属性,您可以在XAML中引用该属性。

2.自行建立系结

您可以自己创建一个 custom“TextChanged”属性的绑定,但这会更复杂,而且可能需要额外的努力才能获得相同的结果。您还需要创建一个可绑定的“Text”属性。下面的代码未经测试,但是使用我在Xamarin.FormsInputView类中找到的绑定(这是Entry的派生来源)。如果您不按照#1的方式进行操作,则需要执行以下操作。向XAML公开可绑定属性如下所示:

public class MyView : ContentView
{

    public MyView()
    {
        InitializeComponent();
    }

    public string Text
    {
        get
        {
            return (string)GetValue(TextProperty);
        }
        set
        {
            SetValue(TextProperty, value);
        }
    }

    public static readonly BindableProperty TextProperty = BindableProperty.Create("Text", typeof(string), typeof(MyView), defaultValue: "", propertyChanged: 
        (bindable, oldValue, newValue) => ((MyView)bindable).OnTextChanged((string)oldValue, (string)newValue));

    public event EventHandler<TextChangedEventArgs> TextChanged;

    protected virtual void OnTextChanged(string oldValue, string newValue)
    {
        TextChanged?.Invoke(this, new TextChangedEventArgs(oldValue, newValue));
    }
}

我希望我更全面的回答能帮助你选择你想要的方向。如果你想了解更多关于Bindable Properties的信息,请查看Edward的链接。

相关问题