locked
Bind Grid using MVVM in windows phone app RRS feed

  • Question

  • How to bind grid consistes of  textbox and listbox using MVVM in windows phone apps and get the selected item in this listbox  

    DesertQueen


    • Edited by DevWP Wednesday, September 11, 2013 11:17 AM update
    Wednesday, September 11, 2013 9:05 AM

Answers

  • Hi,

    Now its working fine.

    You need to make changes on following

    1)In TestSurvay.xaml.cs page

    protected  override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
            {
                base.OnNavigatedTo(e);
                loadingProgressBar.IsVisible = true;
                PollsViewModel pollsViewModel = new PollsViewModel();
                pollsViewModel.loadData();
                this.DataContext = pollsViewModel;
                txtQuestion.Text = pollsViewModel.Poll.Polls_Question;
                lstAnswersLst.ItemsSource = pollsViewModel.Poll.Lst_Polls_Answer_Questions;
                loadingProgressBar.IsVisible = false;
               // txtQuestion.Text = pollsViewModel.Polls[0].Polls_Question;
            }

    2)In your xaml

     <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"  >
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="41*"/>
                    
                </Grid.ColumnDefinitions>
                <Grid.DataContext>
                    <Binding Source="PollsViewModel" />
                </Grid.DataContext>
                <TextBlock  Name="txtQuestion" Text="{Binding Polls_Question}"  Height="49" VerticalAlignment="Top"  Tag="ID" Margin="0,3,0,0"/>
                <ListBox    HorizontalAlignment="Left" x:Name="lstAnswersLst" SelectionMode="Single"  VerticalAlignment="Bottom" Width="454" FontWeight="Bold" Height="358" Margin="2,0,0,226" ItemsSource="{Binding Polls.Lst_Polls_Answer_Questions}" >
                    <ListBox.ItemsPanel>
                        <ItemsPanelTemplate>
                            <toolkit:WrapPanel ItemWidth="430" />
                        </ItemsPanelTemplate>
                    </ListBox.ItemsPanel>
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel  Orientation="Vertical" >
                                <Image   x:Name="imgCellbg" Source="Images/barBook.png"   Margin="5,10,0,10" Stretch="Fill"  Width="425" Tag="{Binding ID }" Tap="imgCellbg_Tap_1" />
                                <TextBlock Margin="170,-60,0,0"   x:Name="txtAnswer" Text="{Binding Polls_Answer }"  Foreground="#2b5734" FontSize="20"   />
                                <Image   x:Name="ckbItem"    Source="Images/check_right_1.png" HorizontalAlignment="Left" Margin="20,-55,0,0" VerticalAlignment="Top" Height="40"  Width="80"  Tap="ckbItem_Tap_1" Tag="{Binding Polls_Votes }" />
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
    
                </ListBox>
                <Button Content="vote" HorizontalAlignment="Left" Margin="6,587,0,0" VerticalAlignment="Top" Tap="Button_Tap_1" Grid.Column="1"/>
            </Grid>
        </Grid>

    3)Put  global " public QuestionModel Poll " in PollsViewModel class some like this;

    namespace TestServices.ViewModel
    {
        public  class PollsViewModel
        {
    
           
            private ObservableCollection<QuestionModel> _Polls = new ObservableCollection<QuestionModel>();
            public ObservableCollection<QuestionModel> Polls
            {
                get
                {
                    return _Polls;
                }
                set
                {
                    _Polls = value;
                }
            }
            public QuestionModel Poll;
            public void loadData()
            {
                
                Poll = new QuestionModel();
                Poll.ID = "1";
                Poll.Polls_Question = "Q1";
                List<AnswerModel> lstAsnwer = new List<AnswerModel>();
                lstAsnwer.Add(new AnswerModel() { ID = "1", Polls_Answer = "a1", Polls_Votes = "5" });
                lstAsnwer.Add(new AnswerModel() { ID = "2", Polls_Answer = "a2", Polls_Votes = "7" });
                lstAsnwer.Add(new AnswerModel() { ID = "2", Polls_Answer = "a2", Polls_Votes = "9" });
                Poll.Lst_Polls_Answer_Questions = lstAsnwer;
                Polls.Add(Poll);
            }
            
        }
    }

    Thanks, have a nice day.
    • Edited by Subramanyam Raju Wednesday, September 11, 2013 12:56 PM
    • Marked as answer by DevWP Wednesday, September 11, 2013 1:10 PM
    Wednesday, September 11, 2013 12:54 PM

All replies

  • Could you explain what do you want bind at TextBlock and why do you need to use MVVM?

    You can add x:Name to your listbox and bing it by ElementName.

    For example

    <TextBlcok Text={Binding SelectedIndex, ElementName='listbox' />

    Wednesday, September 11, 2013 9:15 AM
  • i want to learn MVVM and use it in wp app
    as i have complicated Model View   which contains object with Polls (ID ,Question ,List<answers>) i want to bind textbox with question and Listbox with List<answers>   with radio button so i only choose only one answer and take the selected answerID when press submit using MVVM Pattern Design

    DesertQueen




    • Proposed as answer by Eduard Porchinskiy Wednesday, September 11, 2013 11:12 AM
    • Unproposed as answer by Eduard Porchinskiy Wednesday, September 11, 2013 11:12 AM
    • Edited by DevWP Wednesday, September 11, 2013 11:17 AM update
    Wednesday, September 11, 2013 9:24 AM
  • Hi, bind the field Question to TextBlock property Text at the first. Then bind field List<answers> to ItemsSource. For example,

    <!---xmlns:vm="Your path to VM" --->
    
    <PhoneApplicationPage.Resource>
         <vm:YourViewModel x:Key="YourViewModel" />
    </PhoneApplicationPage.Resource>
    
    <DataContext>
         <Binding Source="YourViewModel" />
    </DataContext>
    
    <!---......--->
    <StackPanel>
    <TextBlock Text="{Binding Poll.Question, Source="{StaticResource YourViewModel}}" />
    <ListBox x:Name="answersList"
     ItemsSource="{Poll.Answers, Source="{StaticResource YourViewModel}}">
    <!---......--->
    </ListBox>
    <Button Content="Send"
    Command="{Binding AnswerCommand, Source="{StaticResource YourViewModel}}"
    CommandParameter="{Binding SelectedIndex, ElementName='answersList'} />

    • Proposed as answer by Oleg Kurzov Wednesday, September 11, 2013 11:43 AM
    • Unproposed as answer by DevWP Wednesday, September 11, 2013 11:44 AM
    Wednesday, September 11, 2013 11:29 AM
  • I get nothing in the screen

    DesertQueen

    Wednesday, September 11, 2013 11:46 AM
  • Please, share full code of your ViewModel. Eduard provide good example how to use binding in MVVM and his code is work. 
    • Edited by Oleg Kurzov Wednesday, September 11, 2013 11:48 AM
    Wednesday, September 11, 2013 11:47 AM
  • public

    classQuestionModel: INotifyPropertyChanged


        {

           

    publicstringID { get; set; }

           

    publicstringPolls_Question { get; set; }

           

    publicList<AnswerModel> Lst_Polls_Answer_Questions { get; set; }

           

    publiceventPropertyChangedEventHandlerPropertyChanged;

           

    privatevoidRaisePropertyChanged(stringpropertyName)

            {

               

    if(this.PropertyChanged != null)

                {

                   

    this.PropertyChanged(this, newPropertyChangedEventArgs(propertyName));

                }

            }

           

    // Create a copy of an MyBudget to save.


           

    // If your object is databound, this copy is not databound.


           

    publicQuestionModelGetCopy()

            {

               

    QuestionModelcopy = (QuestionModel)this.MemberwiseClone();

               

    returncopy;

            }

        }


    DesertQueen

    Wednesday, September 11, 2013 11:54 AM
  • public

    classAnswerModel: INotifyPropertyChanged


        {

           

    publicstringID { get; set; }

           

    publicstringPolls_Votes { get; set; }

           

    publicstringPolls_Answer { get; set; }

           

    publiceventPropertyChangedEventHandlerPropertyChanged;

           

    privatevoidRaisePropertyChanged(stringpropertyName)

            {

               

    if(this.PropertyChanged != null)

                {

                   

    this.PropertyChanged(this, newPropertyChangedEventArgs(propertyName));

                }

            }

           

    // Create a copy of an MyBudget to save.


           

    // If your object is databound, this copy is not databound.


           

    publicAnswerModelGetCopy()

            {

               

    AnswerModelcopy = (AnswerModel)this.MemberwiseClone();

               

    returncopy;

            }


    DesertQueen

    Wednesday, September 11, 2013 11:54 AM
  • public

      classPollsViewModel


        {

    privateObservableCollection<QuestionModel> _Polls = newObservableCollection<QuestionModel>();

           

    publicObservableCollection<QuestionModel> Polls

            {

               

    get


                {

                   

    return_Polls;

                }

               

    set


                {

                    _Polls =

    value;

                }

            }

           

    publicvoidloadData()

            {

               

    QuestionModelPoll;

                Poll =

    newQuestionModel();

                Poll.ID =

    "1";

                Poll.Polls_Question =

    "Q1";

               

    List<AnswerModel> lstAsnwer = newList<AnswerModel>();

                lstAsnwer.Add(

    newAnswerModel() { ID = "1", Polls_Answer = "a1", Polls_Votes = "5"});

                lstAsnwer.Add(

    newAnswerModel() { ID = "2", Polls_Answer = "a2", Polls_Votes = "7"});

                lstAsnwer.Add(

    newAnswerModel() { ID = "2", Polls_Answer = "a2", Polls_Votes = "9"});

                Poll.Lst_Polls_Answer_Questions = lstAsnwer;

                Polls.Add(Poll);

            }

    }


    DesertQueen

    Wednesday, September 11, 2013 11:56 AM
  • Hi ,

    Can u share it on sky drive. Because its having more objects and so we are unable to test your source code and reproduce solution .

    Thanks, 


    Wednesday, September 11, 2013 12:06 PM
  • ok i'll upload it

    DesertQueen

    Wednesday, September 11, 2013 12:07 PM
  • Hi,

    Now its working fine.

    You need to make changes on following

    1)In TestSurvay.xaml.cs page

    protected  override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
            {
                base.OnNavigatedTo(e);
                loadingProgressBar.IsVisible = true;
                PollsViewModel pollsViewModel = new PollsViewModel();
                pollsViewModel.loadData();
                this.DataContext = pollsViewModel;
                txtQuestion.Text = pollsViewModel.Poll.Polls_Question;
                lstAnswersLst.ItemsSource = pollsViewModel.Poll.Lst_Polls_Answer_Questions;
                loadingProgressBar.IsVisible = false;
               // txtQuestion.Text = pollsViewModel.Polls[0].Polls_Question;
            }

    2)In your xaml

     <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"  >
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="41*"/>
                    
                </Grid.ColumnDefinitions>
                <Grid.DataContext>
                    <Binding Source="PollsViewModel" />
                </Grid.DataContext>
                <TextBlock  Name="txtQuestion" Text="{Binding Polls_Question}"  Height="49" VerticalAlignment="Top"  Tag="ID" Margin="0,3,0,0"/>
                <ListBox    HorizontalAlignment="Left" x:Name="lstAnswersLst" SelectionMode="Single"  VerticalAlignment="Bottom" Width="454" FontWeight="Bold" Height="358" Margin="2,0,0,226" ItemsSource="{Binding Polls.Lst_Polls_Answer_Questions}" >
                    <ListBox.ItemsPanel>
                        <ItemsPanelTemplate>
                            <toolkit:WrapPanel ItemWidth="430" />
                        </ItemsPanelTemplate>
                    </ListBox.ItemsPanel>
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel  Orientation="Vertical" >
                                <Image   x:Name="imgCellbg" Source="Images/barBook.png"   Margin="5,10,0,10" Stretch="Fill"  Width="425" Tag="{Binding ID }" Tap="imgCellbg_Tap_1" />
                                <TextBlock Margin="170,-60,0,0"   x:Name="txtAnswer" Text="{Binding Polls_Answer }"  Foreground="#2b5734" FontSize="20"   />
                                <Image   x:Name="ckbItem"    Source="Images/check_right_1.png" HorizontalAlignment="Left" Margin="20,-55,0,0" VerticalAlignment="Top" Height="40"  Width="80"  Tap="ckbItem_Tap_1" Tag="{Binding Polls_Votes }" />
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
    
                </ListBox>
                <Button Content="vote" HorizontalAlignment="Left" Margin="6,587,0,0" VerticalAlignment="Top" Tap="Button_Tap_1" Grid.Column="1"/>
            </Grid>
        </Grid>

    3)Put  global " public QuestionModel Poll " in PollsViewModel class some like this;

    namespace TestServices.ViewModel
    {
        public  class PollsViewModel
        {
    
           
            private ObservableCollection<QuestionModel> _Polls = new ObservableCollection<QuestionModel>();
            public ObservableCollection<QuestionModel> Polls
            {
                get
                {
                    return _Polls;
                }
                set
                {
                    _Polls = value;
                }
            }
            public QuestionModel Poll;
            public void loadData()
            {
                
                Poll = new QuestionModel();
                Poll.ID = "1";
                Poll.Polls_Question = "Q1";
                List<AnswerModel> lstAsnwer = new List<AnswerModel>();
                lstAsnwer.Add(new AnswerModel() { ID = "1", Polls_Answer = "a1", Polls_Votes = "5" });
                lstAsnwer.Add(new AnswerModel() { ID = "2", Polls_Answer = "a2", Polls_Votes = "7" });
                lstAsnwer.Add(new AnswerModel() { ID = "2", Polls_Answer = "a2", Polls_Votes = "9" });
                Poll.Lst_Polls_Answer_Questions = lstAsnwer;
                Polls.Add(Poll);
            }
            
        }
    }

    Thanks, have a nice day.
    • Edited by Subramanyam Raju Wednesday, September 11, 2013 12:56 PM
    • Marked as answer by DevWP Wednesday, September 11, 2013 1:10 PM
    Wednesday, September 11, 2013 12:54 PM