如何在后端C#和渲染器之间共享字段的值?

时间:2017-12-23 08:32:32

标签: xamarin xamarin.forms

我的C#看起来像这样:

mgfinancewindow

我有一个标签页的iOS渲染器

public App()
{
   InitializeComponent();
   MainPage = new Japanese.MainPage();
}

public partial class MainPage : TabbedPage
{

    public MainPage()
    {
        InitializeComponent();

        var phrasesPage = new NavigationPage(new PhrasesPage())
        {
            Title = "Play",
            Icon = "ionicons-2-0-1-ios-play-outline-25.png"

        };

public partial class PhrasesPage : ContentPage
{
    public PhrasesFrame phrasesFrame;

    public PhrasesPage()
    {
        InitializeComponent();
        NavigationPage.SetHasNavigationBar(this, false);
        App.phrasesPage = this;
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();
        App.dataChange = true;
        phrasesFrame = new PhrasesFrame(this);
        phrasesStackLayout.Children.Add(phrasesFrame);
    }

public partial class PhrasesFrame : Frame
{

    private async Task ShowCard()
    {
        if (pauseCard == false) 
        ..

我的问题是两者之间没有任何关联,我想知道如何制作它以便pauseCard可以设置在一个地方并在另一个地方读取。

1 个答案:

答案 0 :(得分:2)

这是一个简单的自定义Entry示例,它使用可绑定的bool属性,每次文本在条目中发生更改时,该属性都会从渲染器中更改。

具有名为OnOff(bool

的可绑定属性的Entry子类
public class CustomPropertyEntry : Entry
{
    public static readonly BindableProperty OnOffProperty = BindableProperty.Create(
        propertyName: "OnOff",
        returnType: typeof(bool),
        declaringType: typeof(CustomPropertyEntry),
        defaultValue: false);

    public bool OnOff
    {
        get { return (bool)GetValue(OnOffProperty); }
        set { SetValue(OnOffProperty, value); }
    }
}

iOS渲染器

注意:我保留对CustomPropertyEntry传递给OnElementChanged的实例的引用,以便稍后我可以在需要时设置其自定义属性。

public class CustomPropertyEntryRenderer : ViewRenderer<CustomPropertyEntry, UITextField>
{
    UITextField textField;
    CustomPropertyEntry entry;

    protected override void OnElementChanged(ElementChangedEventArgs<CustomPropertyEntry> e)
    {
        base.OnElementChanged(e);

        if (Control == null)
        {
            textField = new UITextField();
            SetNativeControl(textField);
        }
        if (e.OldElement != null)
        {
            textField.RemoveTarget(EditChangedHandler, UIControlEvent.EditingChanged);
            entry = null;
        }
        if (e.NewElement != null)
        {
            textField.AddTarget(EditChangedHandler, UIControlEvent.EditingChanged);
            entry = e.NewElement;
        }
    }

    void EditChangedHandler(object sender, EventArgs e)
    {
        entry.OnOff = !entry.OnOff;
    }
}

XAML示例:

<local:CustomPropertyEntry x:Name="customEntry" Text="" />
<Switch BindingContext="{x:Reference customEntry}" IsToggled="{Binding OnOff}" />

enter image description here