Forum Xamarin.Forms

How to reveice a paramater in ViewModel?

I send a parameter from view using button:
public async void btnchat_clicked(object sender, EventArgs e)
{
string sellerid = custid.Text;
await Navigation.PushAsync(new ChatPageViewModel(sellerid.ToString()));
}
i need help for how to receive the value in viewmodel for where clause

Best Answers

  • jezhjezh Member, Xamarin Team Xamurai
    edited November 2020 Accepted Answer

    await Navigation.PushAsync(new ChatPageViewModel(sellerid.ToString()));

    If we want to navigate to another page ,we couldn't use the Viewmodel of a Page as the parameter of function Navigation.PushAsync().

    If we want to pass some values to another page when we navigate from one page.
    we can pass the values by the constructor of the page.

    For example:

            private async void Button_ClickedAsync(object sender, EventArgs e)
            {
                string sellerid = "test string...";
                await Navigation.PushAsync(new TestPage(sellerid));
            }
    

    TestPage.xaml.cs

        public partial class TestPage : ContentPage
        {
            string myValue;
            public TestPage( string str)
            {
                InitializeComponent();
    
                myValue = str;
            }
        }
    

    Xamarin forums are migrating to a new home on Microsoft Q&A!
    We invite you to post new questions in the Xamarin forums’ new home on Microsoft Q&A!
    For more information, please refer to this sticky post.

  • ShrikantPShrikantP Member ✭✭
    Accepted Answer

    @jezh said:
    And I found you have two constructors in your viewmodel ChatPageViewModel.

    I don't think it is the right way to do this.

    You can just use one constructor which has one parameter(SellerChatID) .

    public class ChatPageViewModel : INotifyPropertyChanged
    {
    
        public ObservableCollection<Message> Messages { get; set; } = new ObservableCollection<Message>();
        public string TextToSend { get; set; }
        public ICommand OnSendCommand { get; set; }
    
    
        private string sellerChatID;
    
        //Change below here
        public ChatPageViewModel(string SellerChatID)
        {
            this.sellerChatID = SellerChatID;
    
           //add other code here
    
          
        }
    }
    

    Yes true. i can use single constructor also and i tried every thing i didn't get a output. and not a error.
    how to show a output

Answers

  • jezhjezh Member, Xamarin Team Xamurai
    edited November 2020 Accepted Answer

    await Navigation.PushAsync(new ChatPageViewModel(sellerid.ToString()));

    If we want to navigate to another page ,we couldn't use the Viewmodel of a Page as the parameter of function Navigation.PushAsync().

    If we want to pass some values to another page when we navigate from one page.
    we can pass the values by the constructor of the page.

    For example:

            private async void Button_ClickedAsync(object sender, EventArgs e)
            {
                string sellerid = "test string...";
                await Navigation.PushAsync(new TestPage(sellerid));
            }
    

    TestPage.xaml.cs

        public partial class TestPage : ContentPage
        {
            string myValue;
            public TestPage( string str)
            {
                InitializeComponent();
    
                myValue = str;
            }
        }
    

    Xamarin forums are migrating to a new home on Microsoft Q&A!
    We invite you to post new questions in the Xamarin forums’ new home on Microsoft Q&A!
    For more information, please refer to this sticky post.

  • ShrikantPShrikantP Member ✭✭

    Thanks for Replying
    but i tried to create a chat system using this. when the login in person click the button then login person start chat with selected person and i am using mvvm. So i am write a code in vm. I want this for load a previous chat from database.
    If Their is another solution plz help i tried every thing..

  • jezhjezh Member, Xamarin Team Xamurai

    I want this for load a previous chat from database.

    Can you describe your problem in detail?

    await Navigation.PushAsync(new ChatPageViewModel(sellerid.ToString()));

    When you click a Button, do you want to navigate to another page and pass some value at the same time?

  • ShrikantPShrikantP Member ✭✭

    @jezh said:

    I want this for load a previous chat from database.

    Can you describe your problem in detail?

    await Navigation.PushAsync(new ChatPageViewModel(sellerid.ToString()));

    When you click a Button, do you want to navigate to another page and pass some value at the same time?

    I m trying to create a application with register user can send a message to selected user.
    when login user can see the other user profile their is button to chat or send a message.
    when login user click the button for start chat it will open a new page with previous chat history if availble, for this i m tring to use mvvm for shows a previous chat history between these two users.
    So my problem is i cann't get the selected user id for search in data from database using where clause.

  • ShrikantPShrikantP Member ✭✭

    @jezh said:

    I want this for load a previous chat from database.

    Can you describe your problem in detail?

    await Navigation.PushAsync(new ChatPageViewModel(sellerid.ToString()));

    When you click a Button, do you want to navigate to another page and pass some value at the same time?

    Hello, plz help me. if possible.....!

  • jezhjezh Member, Xamarin Team Xamurai

    when login user click the button for start chat it will open a new page with previous chat history if availble, for this i m tring to use mvvm for shows a previous chat history between these two users.

    Where is the a previous chat history? What is its relationship to the current page(including the button for start chat) and the new page?

  • ShrikantPShrikantP Member ✭✭
    edited December 2020

    @jezh said:

    when login user click the button for start chat it will open a new page with previous chat history if availble, for this i m tring to use mvvm for shows a previous chat history between these two users.

    Where is the a previous chat history? What is its relationship to the current page(including the button for start chat) and the new page?

    I write in details

    ChatHome.xaml //Show the all registered user in listview
    In this page their is list of all users and click any user opens a user details

    ChatUser.xaml // here shows a selected user details. I added only required cells/parameters

    <ScrollView HeightRequest="3000" BackgroundColor="#ffffff">
                <StackLayout Spacing="10" Padding="5,0,5,0">
    
                     <Grid Margin="10,0,10,0" >
                        <Grid.RowDefinitions>
                            <RowDefinition Height="auto"/>
                            <RowDefinition Height="auto"/>
                            <RowDefinition Height="auto"/>
    
                        </Grid.RowDefinitions>
                   <Grid.ColumnDefinitions>
                            <ColumnDefinition />
                            <ColumnDefinition />
                        </Grid.ColumnDefinitions>
    
    
                    <StackLayout Grid.Row="0" Grid.ColumnSpan="2" Margin="0,10,0,10">
                         <Label Text="{Binding custname}" x:Name="custname" FontSize="16"
                                FontAttributes="Bold"/><Label Text="{Binding custid}" x:Name="custid" FontSize="16"
                                FontAttributes="Bold"/>
                    </StackLayout>
            <StackLayout Grid.Row="1" Grid.ColumnSpan="2" Margin="0,10,0,10">
                         <Label Text="{Binding custemail}" x:Name="custemail" FontSize="16"/>
                    </StackLayout>
                    <StackLayout Grid.Row="2" Grid.ColumnSpan="2" Margin="0,10,0,10">
                        <Button x:Name="btnchat" TextColor="#ffffff" VerticalOptions="Center" HorizontalOptions="Center"
                                    Text="Chat with seller" FontSize="15" CornerRadius="15"
                                Clicked="btnchat_clicked" 
                                CommandParameter="{Binding custid}">
                                 <Button.Background>
                                    <LinearGradientBrush EndPoint="1,0">
                                        <GradientStop Color="#468f86" Offset="0.1" />
                                        <GradientStop Color="#6fb696" Offset="1.0" />
                                    </LinearGradientBrush>
                                </Button.Background>
                            </Button>
                    </StackLayout>
    
              </Grid>  
    
                </StackLayout>
            </ScrollView>
    
    

    ChatUser.xaml.cs

    public partial class ProductDetailPage : ContentPage
        {
            public ProductDetailPage(string custid)
            {
                InitializeComponent();
    
                custid.Text = custid;
                loadcust();
            }
    
            private void loadcust()
            {
    
                MySqlConnection conn = new MySqlConnection(Constants.connString);
                conn.Open();
                try
                {
                    MySqlCommand cmd = new MySqlCommand("SELECT c.id, c.custname, c.custemail FROM md_customer as c WHERE c.id= '" + custid.Text + "'", conn);
                    MySqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    if (dr.Read())
                    {
                        custid.Text = dr[0].ToString();
                custname.Text = dr[1].ToString();   
                custemail.Text = dr[2].ToString();
                    }
                }
                finally
                {
                    conn.Clone();
                }
    
            }
    
            public async void btnchat_clicked(object sender, EventArgs e)   // I need here help
            {
    
                string sellerid = custid.Text;      //How send this id to viewmodel page, below is code
                //await Navigation.PushAsync(new ChatPage(sellerid));   //if i send this how to load chat history
                await Navigation.PushAsync(new ChatPageViewModel(sellerid));  //If i use this give a error.
            }
        }
    
    

    //////////////////////////////////
    //Now the page will show a chat page with selected user
    Chatpage.xmal

    <ContentPage.Resources>
            <ResourceDictionary>
                <local:ChatTemplateSelector x:Key="MessageTemplateSelector"/>
            </ResourceDictionary>
        </ContentPage.Resources>
        <Grid RowSpacing="0" ColumnSpacing="0">
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition Height="1" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>
            <!-- Our Chat Views Here -->
    
            <ListView Grid.Row="0" Grid.ColumnSpan="2" x:Name="ChatList"
                     ItemTemplate="{StaticResource MessageTemplateSelector}" 
                     ItemsSource="{Binding Messages}" 
                     Margin="0" 
                     HasUnevenRows="True" 
                     VerticalOptions="FillAndExpand" 
                     SeparatorColor="Transparent" >
            </ListView>
            <BoxView HorizontalOptions="FillAndExpand"
                     HeightRequest="1"
                     BackgroundColor="LightGray"
                     Grid.Row="1"/>
     <Entry x:Name="chatTextInput" 
                             Text="{Binding TextToSend}" 
                             Margin="1"  
                             TextColor="Black" 
                             Keyboard="Chat"  
                             HorizontalOptions="FillAndExpand" 
                             PlaceholderColor="LightGray"
                             Placeholder="Type here" FontSize="14"
                             Grid.Row="2" 
                             Grid.Column="0" WidthRequest="70" />
            <ImageButton Source="plane.png" WidthRequest="30" HeightRequest="30" HorizontalOptions="End"
                             Grid.Row="2" Grid.Column="1" BackgroundColor="Transparent" Margin="0,0,7,0"
                                 Clicked="btnChat_Clicked"/>
    </Grid>
    

    //Now here i want to
    ChatPageViewModel.cs

    public class ChatPageViewModel : INotifyPropertyChanged
        {
    
            public ObservableCollection<Message> Messages { get; set; } = new ObservableCollection<Message>();
            public string TextToSend { get; set; }
            public ICommand OnSendCommand { get; set; }
    
            public ChatPageViewModel()
            {
    
          string fromuserid = Application.Current.Properties["userid"].ToString();
    
                MySqlConnection conn = new MySqlConnection(Constants.connString);
                conn.Open();
    //
        // below here i use id numbers 
    // insted of number i want to use parameters
                string sqlcat = "select to_user_id, from_user_id, chat_message, timestamp from chat_message where from_user_id = '" + fromuserid.ToString() + "' and to_user_id = '1' or from_user_id = '1' and to_user_id = '" + fromuserid.ToString() + "' order by timestamp";
                MySqlCommand cmd = new MySqlCommand(sqlcat, conn);
                MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                sda.Fill(dt);
                Messages = new ObservableCollection<Message>();
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i]["from_user_id"].ToString() == fromuserid.ToString())
                        {
                            Messages.Add(new Message() { Text = dt.Rows[i]["chat_message"].ToString(), User = fromuserid.ToString() });
    
                        }
    
                        if (dt.Rows[i]["from_user_id"].ToString() == "1")
                        {
                            Messages.Add(new Message { Text = dt.Rows[i]["chat_message"].ToString() });
    
                        }
    
                    }
                }
    
    
                        OnSendCommand = new Command(() =>
                {
                    if (!string.IsNullOrEmpty(TextToSend))
                    {
                        Messages.Add(new Message() { Text = TextToSend, User = fromuserid.ToString() });
                        TextToSend = string.Empty;
                    }
    
                });
    
    
            }
    
    
            public event PropertyChangedEventHandler PropertyChanged;
    
        }
    
    

    Chatpage.xaml.cs

    public partial class ChatPage : ContentPage
        {
            string SellerChatID;
    
            public ChatPage()
            {
                InitializeComponent();
                if (Application.Current.Properties.ContainsKey("userid"))
                {
                    string fromuserid = Application.Current.Properties["userid"].ToString();
    
                }
    
                BindingContext = new ChatPageViewModel();
               //loadChat();
    
            }
    
    
    
            public void OnListTapped(object sender, ItemTappedEventArgs e)
            {
                //chatInput.UnFocusEntry();
            }
    
            private async void btnChat_Clicked(object sender, EventArgs e)
            {
                MySqlConnection conn = new MySqlConnection(Constants.connString);
                await conn.OpenAsync();
    
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = Constants.insertChat;
                cmd.Parameters.Add("@to_user", MySqlDbType.VarChar).Value = SellerChatID.ToString();
                cmd.Parameters.Add("@from_user", MySqlDbType.VarChar).Value = Application.Current.Properties["userid"].ToString();
                cmd.Parameters.Add("@chat_message", MySqlDbType.VarChar).Value = chatTextInput.Text;
                cmd.Parameters.Add("@waqt", MySqlDbType.VarChar).Value = DateTime.Now;
                cmd.Parameters.Add("@status", MySqlDbType.VarChar).Value = '1';
    
                await cmd.ExecuteNonQueryAsync();
                conn.Close();
    
                BindingContext = new ChatPageViewModel();
    
                //@to_user,@from_user,@chat_message,@waqt,@status
            }
    
    
        }
    
    

    Plz get this if u understand

  • igorkr_10igorkr_10 Member ✭✭✭✭

    You can use Shell with it's uri navigation
    Or try Prism

    Another way is more simple.
    Create public property in page to get ViewModel from anywhere.

    public YourViewModel ViewModel
            {
                get { return (YourViewModel)this.BindingContext; }
            }
    
    public YourPage()
            {
                InitializeComponent();
            }
    

    And then use it:

    YourPage yourPage=new YourPage();
    yourPage.ViewModel.Id=id;
    await Navigation.PushAsync(yourPage);
    
  • ShrikantPShrikantP Member ✭✭
    edited December 2020

    @igorkr_10 said:
    You can use Shell with it's uri navigation
    Or try Prism

    Another way is more simple.
    Create public property in page to get ViewModel from anywhere.

    public YourViewModel ViewModel
            {
                get { return (YourViewModel)this.BindingContext; }
            }
    
    public YourPage()
            {
                InitializeComponent();
            }
    

    And then use it:

    YourPage yourPage=new YourPage();
    yourPage.ViewModel.Id=id;
    await Navigation.PushAsync(yourPage);
    

    Sorry i didn't get..

  • jezhjezh Member, Xamarin Team Xamurai
            public async void btnchat_clicked(object sender, EventArgs e)   // I need here help
            {
    
                string sellerid = custid.Text;      //How send this id to viewmodel page, below is code
                //await Navigation.PushAsync(new ChatPage(sellerid));   //if i send this how to load chat history
                await Navigation.PushAsync(new ChatPageViewModel(sellerid));  //If i use this give a error.
            }
    

    If I understand correctly, do you want to pass the sellerid from page ChatUser to ChatPage and pass the sellerid to viewmodel ChatPageViewModel, right?

    Then you can do like this:

        public async void btnchat_clicked(object sender, EventArgs e)   // I need here help
        {
    
            string sellerid = custid.Text;      
            await Navigation.PushAsync(new ChatPage(sellerid));  
        }
    

    and in ChatPage page, you can pass the sellerid to model ChatPageViewModel by the constructor of ChatPageViewModel:

        public partial class ChatPage: ContentPage
        {
            string myValue;
            public ChatPage( string str)
            {
                InitializeComponent();
    
                myValue = str;
    
                BindingContext = new ChatPageViewModel(myValue);
            }
        }
    
  • ShrikantPShrikantP Member ✭✭
    edited December 2020

    @jezh said:

            public async void btnchat_clicked(object sender, EventArgs e)   // I need here help
            {
    
                string sellerid = custid.Text;      //How send this id to viewmodel page, below is code
                //await Navigation.PushAsync(new ChatPage(sellerid));   //if i send this how to load chat history
                await Navigation.PushAsync(new ChatPageViewModel(sellerid));  //If i use this give a error.
            }
    

    If I understand correctly, do you want to pass the sellerid from page ChatUser to ChatPage and pass the sellerid to viewmodel ChatPageViewModel, right?

    Then you can do like this:

        public async void btnchat_clicked(object sender, EventArgs e)   // I need here help
        {
    
            string sellerid = custid.Text;      
            await Navigation.PushAsync(new ChatPage(sellerid));  
        }
    

    and in ChatPage page, you can pass the sellerid to model ChatPageViewModel by the constructor of ChatPageViewModel:

        public partial class ChatPage: ContentPage
        {
            string myValue;
            public ChatPage( string str)
            {
                InitializeComponent();
    
                myValue = str;
    
                BindingContext = new ChatPageViewModel(myValue);
            }
        }
    

    i used your code but i got a error on the ChatUser.xaml page load,
    Error: System.NullReferenceException Object reference not set to an instance of an object.
    Here is the Code:

    UserList.xaml

    <ContentPage.Content>


    <ListView.ItemTemplate>


                        <Grid Padding="1" RowSpacing="10" ColumnSpacing="10" BackgroundColor="#ffffff">
    
                              <Grid.RowDefinitions>
                                  <RowDefinition Height="auto"/>
                                  <RowDefinition Height="*"/>
                              </Grid.RowDefinitions>
                              <Grid.ColumnDefinitions>
                                  <ColumnDefinition Width="Auto"/>
                                  <ColumnDefinition Width="*"/>
                              </Grid.ColumnDefinitions>
    
                         <!-- -->
                              <Label Grid.Column="1"  Text="{Binding custname}" VerticalOptions="End" TextColor="#3a3e4a"
                                     FontSize="16" FontAttributes="Bold"/>
                            <Label Grid.Column="1" Grid.Row="1" Text="&#x20b9;" FontAttributes="Bold"
                                     VerticalOptions="Start" TextColor="#ff5161" FontSize="14"/>
                              <Label Grid.Column="1" Grid.Row="1" Text="{Binding city}" Padding="10,0,0,0"
                                      FontAttributes="Bold" VerticalOptions="Start" TextColor="#ff5161" FontSize="14"/>
                              <Label Grid.Column="1" Text="{Binding custID}" VerticalOptions="End" TextColor="#3a3e4a"
                                     />
                          </Grid>
                            </Frame>
                      </ViewCell>
                    </DataTemplate>
                 </ListView.ItemTemplate>
                <!--/////-->
             </ListView>
    </ContentPage.Content>
    

    =========
    UserList.xaml.cs

    public partial class CustomerHomePage : ContentPage
    {
    public CustomerHomePage()
    {
    InitializeComponent();
    BindingContext = new CustomerListViewModel();
    }

    //After CLicking this i got a error
    //Error: System.NullReferenceException Object reference not set to an instance of an object.

        private async void OnCustomerSelected(object sender, ItemTappedEventArgs e)
        {
            var mycustomer = e.Item as CustomerListModel;
            await Navigation.PushAsync(new ProductDetailPage(mycustomer.customerId));
    
        }
    
    }
    

    =======
    CustomerListViewModel.cs
    public class CustomerListViewModel
    {
    //public ImageSource imagePro;
    public ObservableCollectionCustomerList { get; set; }

        public CustomerListViewModel()
        {
    
            MySqlConnection conn = new MySqlConnection(Constants.connString);
            conn.Open();
            string sqlcat = "select custid, custname, city from md_customer";
            MySqlCommand cmd = new MySqlCommand(sqlcat, conn);
            MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            sda.Fill(dt);
    
            CustomerList = new ObservableCollection<CustomerListModel>();
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
    
                    CustomerList.Add(new CustomerListModel {custID = dt.Rows[i]["custid"].ToString(), customername = dt.Rows[i]["custname"].ToString(), city = dt.Rows[i]["city"].ToString() });
    
                }
            }
    
        }
    
  • ShrikantPShrikantP Member ✭✭

    @jezh said:

            public async void btnchat_clicked(object sender, EventArgs e)   // I need here help
            {
    
                string sellerid = custid.Text;      //How send this id to viewmodel page, below is code
                //await Navigation.PushAsync(new ChatPage(sellerid));   //if i send this how to load chat history
                await Navigation.PushAsync(new ChatPageViewModel(sellerid));  //If i use this give a error.
            }
    

    If I understand correctly, do you want to pass the sellerid from page ChatUser to ChatPage and pass the sellerid to viewmodel ChatPageViewModel, right?

    Then you can do like this:

        public async void btnchat_clicked(object sender, EventArgs e)   // I need here help
        {
    
            string sellerid = custid.Text;      
            await Navigation.PushAsync(new ChatPage(sellerid));  
        }
    

    and in ChatPage page, you can pass the sellerid to model ChatPageViewModel by the constructor of ChatPageViewModel:

        public partial class ChatPage: ContentPage
        {
            string myValue;
            public ChatPage( string str)
            {
                InitializeComponent();
    
                myValue = str;
    
                BindingContext = new ChatPageViewModel(myValue);
            }
        }
    

    but didn't show the message; below i update ChatPageViewModel.cs
    public class ChatPageViewModel : INotifyPropertyChanged
    {

        public ObservableCollection<Message> Messages { get; set; } = new ObservableCollection<Message>();
        public string TextToSend { get; set; }
        public ICommand OnSendCommand { get; set; }
    
    
        private string sellerChatID;
    
        //Change below here
        public ChatPageViewModel(string SellerChatID)
        {
            this.sellerChatID = SellerChatID;
        }
    
    
        public ChatPageViewModel()
        {
              string fromuserid = Application.Current.Properties["userid"].ToString();
    
            MySqlConnection conn = new MySqlConnection(Constants.connString);
            conn.Open();
    
            string sqlcat = "select to_user_id, from_user_id, chat_message, timestamp from chat_message where from_user_id = '" + fromuserid.ToString() + "' and to_user_id = '" + this.sellerChatID + "' or from_user_id = '" + this.sellerChatID + "' and to_user_id = '" + fromuserid.ToString() + "' order by timestamp";
            MySqlCommand cmd = new MySqlCommand(sqlcat, conn);
            MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            Messages = new ObservableCollection<Message>();
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i]["from_user_id"].ToString() == fromuserid.ToString())
                    {
                        Messages.Add(new Message() { Text = dt.Rows[i]["chat_message"].ToString(), User = fromuserid.ToString() });
    
                    }
                   //Change below
                    if (dt.Rows[i]["from_user_id"].ToString() == this.sellerChatID)
                    {
                        Messages.Add(new Message { Text = dt.Rows[i]["chat_message"].ToString() });
    
                    }
    
                }
            }
    
                 OnSendCommand = new Command(() =>
            {
                if (!string.IsNullOrEmpty(TextToSend))
                {
                    Messages.Add(new Message() { Text = TextToSend, User = fromuserid.ToString() });
                    TextToSend = string.Empty;
                }
    
            });
    
    
        }
    
    
    
        public event PropertyChangedEventHandler PropertyChanged;
    
    }
    

    and chatpage.xaml.cs code is below ; using this output is not showsing and not error;

    public partial class ChatPage : ContentPage
    {
    string SellerChatID;

        public ChatPage(string sellerid)
        {
            InitializeComponent();
        if (Application.Current.Properties.ContainsKey("userid"))
            {
                string fromuserid = Application.Current.Properties["userid"].ToString();
    
            }
    
            SellerChatID = sellerid;
            //DisplayAlert("Info", SellerChatID, "Ok");
            BindingContext = new ChatPageViewModel(SellerChatID);
    
    
            loadChat();
    
        }
    
        private async void loadChat()
        {
            MySqlConnection conn = new MySqlConnection(Constants.connString);
            conn.Open();
            string sqlcat = "SELECT to_user_id FROM chat_message WHERE to_user_id = '" + lblsellerid.Text + "'";
            MySqlCommand cmd = new MySqlCommand(sqlcat, conn);
            MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                BindingContext = new ChatPageViewModel();
            }
            else
            {
                await DisplayAlert("Chat", "Their is no communication", "OK");
            }
    
    
    
        }
    
        public void OnListTapped(object sender, ItemTappedEventArgs e)
        {
            //chatInput.UnFocusEntry();
        }
    
        private async void btnChat_Clicked(object sender, EventArgs e)
        {
            MySqlConnection conn = new MySqlConnection(Constants.connString);
            await conn.OpenAsync();
    
            MySqlCommand cmd = new MySqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = Constants.insertChat;
            cmd.Parameters.Add("@to_user", MySqlDbType.VarChar).Value = SellerChatID.ToString();
            cmd.Parameters.Add("@from_user", MySqlDbType.VarChar).Value = Application.Current.Properties["userid"].ToString();
            cmd.Parameters.Add("@chat_message", MySqlDbType.VarChar).Value = chatTextInput.Text;
            cmd.Parameters.Add("@waqt", MySqlDbType.VarChar).Value = DateTime.Now;
            cmd.Parameters.Add("@status", MySqlDbType.VarChar).Value = '1';
    
            await cmd.ExecuteNonQueryAsync();
            conn.Close();
    
            BindingContext = new ChatPageViewModel();
    

    //@to_user,@from_user,@chat_message,@waqt,@status
    }

    }
    
  • jezhjezh Member, Xamarin Team Xamurai

    In your ChatPage.xaml.cs, you can get the the value of SellerChatID and pass into your viewmodel ChatPageViewModel, right? What I don't understand is after you set the BindingContext, why would you also reset the BindingContext?

    public partial class ChatPage : ContentPage
    {
    string SellerChatID;
    
        public ChatPage(string sellerid)
        {
            InitializeComponent();
        if (Application.Current.Properties.ContainsKey("userid"))
            {
                string fromuserid = Application.Current.Properties["userid"].ToString();
    
            }
    
            SellerChatID = sellerid;
            //DisplayAlert("Info", SellerChatID, "Ok");
            BindingContext = new ChatPageViewModel(SellerChatID);
    
            loadChat();
        }
    
        private async void loadChat()
        {
          // other code
            if (dt.Rows.Count > 0)
            {
                BindingContext = new ChatPageViewModel();
            }
            else
            {
                await DisplayAlert("Chat", "Their is no communication", "OK");
            }
        }
    }
    
  • jezhjezh Member, Xamarin Team Xamurai

    And I found you have two constructors in your viewmodel ChatPageViewModel.

    I don't think it is the right way to do this.

    You can just use one constructor which has one parameter(SellerChatID) .

    public class ChatPageViewModel : INotifyPropertyChanged
    {
    
        public ObservableCollection<Message> Messages { get; set; } = new ObservableCollection<Message>();
        public string TextToSend { get; set; }
        public ICommand OnSendCommand { get; set; }
    
    
        private string sellerChatID;
    
        //Change below here
        public ChatPageViewModel(string SellerChatID)
        {
            this.sellerChatID = SellerChatID;
    
           //add other code here
    
    
        }
    }
    
  • ShrikantPShrikantP Member ✭✭
    Accepted Answer

    @jezh said:
    And I found you have two constructors in your viewmodel ChatPageViewModel.

    I don't think it is the right way to do this.

    You can just use one constructor which has one parameter(SellerChatID) .

    public class ChatPageViewModel : INotifyPropertyChanged
    {
    
        public ObservableCollection<Message> Messages { get; set; } = new ObservableCollection<Message>();
        public string TextToSend { get; set; }
        public ICommand OnSendCommand { get; set; }
    
    
        private string sellerChatID;
    
        //Change below here
        public ChatPageViewModel(string SellerChatID)
        {
            this.sellerChatID = SellerChatID;
    
           //add other code here
    
          
        }
    }
    

    Yes true. i can use single constructor also and i tried every thing i didn't get a output. and not a error.
    how to show a output

  • jezhjezh Member, Xamarin Team Xamurai

    Could you please post the latest code snippets or a basic demo to github or OneDrive?

  • ShrikantPShrikantP Member ✭✭

    @jezh said:
    Could you please post the latest code snippets or a basic demo to github or OneDrive?

    hi i find where i mistake.
    public ChatPageViewModel(string SellerChatID)
    {
    this.sellerChatID = SellerChatID; //here SellerChatID I mistakely written in small letters..
    //other code
    }

    Thank you for your help sir :) .......

Sign In or Register to comment.