Sami.C
Sami.C

Reputation: 721

Xamarin communication between XAML and code-behind in MVVM

I have no issues accessing MVVM properties in my XAML using data binding, e.g.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="xxxProject.xxxView"
             x:DataType="xxxViewModel"
             xmlns:viewmodels="clr-xxxProject.ViewModels"
             >
        <ContentPage.Content>
        <StackLayout>
               
                <Label Text="{Binding myProperty}" />
...

But how would I access something within my View code-behind? Have I lost the link between the two by using a View Model?

namespace xxxProject
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class xxxView: ContentPage
    {
        public string ACCESS_ME = "hello";
        public xxxView()
        {
            InitializeComponent();
            BindingContext = new xxxViewModel();

        }
    }
}

How would I access "ACCESS_ME" ?

Upvotes: 0

Views: 102

Answers (1)

Liyun Zhang - MSFT
Liyun Zhang - MSFT

Reputation: 14204

When you use a MVVM, the communication between XAML and Page.cs is still existed.

You can still give a name to the control in the xaml such as:

 <Button Text="Test" Clicked="Button_Clicked" x:Name="test"/>

And then do something you want in the page.cs, such as:

private void Button_Clicked(object sender, EventArgs e)
    {
        test.Text = ACCESS_ME;
    }

Upvotes: 1

Related Questions