简体   繁体   中英

Xamarin not finding x:Name on XAML

on my Xamarin project Im having an issue finding x:Name on my MainPage.cs...

This is my class called MainWindowViewModel (small application that should really have been renamed)

private string productName { get; set; }
        public string ProductName
        {
            get => productName;
            set
            {
                productName = value;
                OnPropertyChanged("ProductName");
            }
        }

is my code for my MainPage.xaml so ProductName is bound to one of the entry box (below)

<Entry Grid.Row="8"
               x:Name="productNameEntry"
               Grid.Column="2"
               Grid.ColumnSpan="3"
               Grid.RowSpan="2"
               WidthRequest="120"
               VerticalOptions="Center"
               HorizontalOptions="End"
               Text="{Binding ProductName}"
               Margin="0,0,45,0" />

This is what I currently have in my MainPage.cs

void SaveButton_Clicked(object sender, System.EventArgs e)
        {
            MainWindowViewModel APR = new MainWindowViewModel()
            {
                ProductName = productNameEntry,

            };

I currently have an underline of 'productNameEntry' with an error saying the name does not exist in the current context.

you have to get the string value given from the UI Element by adding .Text use: ProductName = productNameEntry.Text

but it is advisable to use a command since you binded the Text property to your view model

Actually, your binding should be good to go, provided your form/window has

DataContext = {Binding ToYourViewModel}

Then, your data entry textbox which has its text binding to {Binding ProductName} automatically handles the entry and pushes back directly to your view model. Its the magic under the hood of .NET binding in WPF. You don't need to know the control's name in your view model. All you care about is exposing the public property on your view model. The binding from your view will look for a property by the same name. If it finds it, it will automatically pass back and forth whether you are reading from SQL and putting into the public property, or reading it back from whatever a user enters in from the screen.

Just to test, before your form starts, just set

ProductName = "some test value";

Then run your form. You should see the above test value. If you can't, the bindings are not correct. Once you get that corrected, change the value in your form to anything else and then click your button. In the button click event handler method, put a breakpoint at the first line in the method to pause the program and look at the value of ProductName… it should automatically be whatever you typed into it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM