2015-01-23 2 views
1

Привет, ребята Я работаю над Windows Phone 8 application. Здесь у меня возникла проблема с обтеканием текстового блока.wp8 public string не обертывается в программно созданный текстовый блок

Когда мой массив строк не был общедоступным, тогда упаковка работает нормально, а когда я создал свой массив строк, то обертка не работает ...!

Я не могу найти свою ошибку.

Мой код здесь

int a =1; 
    ScrollViewer scroll = new ScrollViewer(); 

    string[] questions = new string[] 
    { "Question :\n What is OOPS? \n\n Answer: \n Object-oriented programming (OOP) is a programming paradigm based on the concept of objects which are data structures that contain data in the form of fields often known as attributes and code in the form of procedures often known as methods. There are a few principle concepts that form the foundation of object-oriented programming: 1- Object \n 2- Class \n 3- Abstraction \n 4- Polymorphism \n 5- Inheritance \n 6- Encapsulation \n 7- Overloading & OverRiding " 
    }; 

    int i; 

    private void showContent() 
    { 
     Grid ContentPanel = new Grid(); 
     ContentPanel.Height = 400; 
     ContentPanel.Width = 440; 

     ContentPanel.Margin = new Thickness(0, 20, 0, 0); 

     scroll.Height = 400; 
     scroll.Width = 440; 
     scroll.VerticalScrollBarVisibility = ScrollBarVisibility.Visible; 
     scroll.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; 

     TextBlock text_question = new TextBlock(); 
     text_question.Height = Double.NaN; 
     text_question.Width = 420; 

     // text_question.Text = "Arsal Are you going.? If user is not login then there at detail page user want to add product in his wish list then there is popup comes .... Please Login There should be align text. when user goes to detail screen then first show batch 42 % off after that shows 0% off. more share button and like button alignment also changes slowly. user can identify easily."; 

     text_question.TextWrapping = TextWrapping.Wrap; 
     text_question.Margin = new Thickness(10, 10, 10, 10); 

     scroll.Content = questions[0]; 
     ContentPanel.Children.Add(scroll); 
     //scroll.Content = questions[i]; 
     TitlePanel.Children.Add(ContentPanel);  
} 

text_question.Text = ""; который прокомментирован в этой функции, обертывается, пока публичная строка не обертывается.

Я хочу использовать строку из любой функции, а затем строку для публики.

 private void next_click(object sender, RoutedEventArgs e) 
     { 

      // MessageBox.Show("Here is Next Question"); 
      a = a + 1; 
      count.Text = a.ToString(); 
      if (a > 1) 
      { 
       previous.IsEnabled = true; 
      } 
      if (a == 5) 
      { 
       next.IsEnabled = false; 
      } 

      if (i >= 0 && i < questions.Length) 
      { 
       i = i + 1; 
       scroll.Content = questions[i];          
      }  
     } 

ответ

0

Глядя на код, который вы публикуемую здесь, этот вопрос, кажется, что вы никогда не добавляя TextBlock со свойством оберточной, установленным в ScrollViewer. Я хотел бы обновить эту строку:

scroll.Content = questions[0]; 

к:

scroll.Content = text_question; 

, а затем манипулировать содержанием text_question в в обработчики событий мыши.


Это сказанное, я думаю, что вы делаете это гораздо сложнее, чем это должно быть, и что делает ваш код UI более сложным, чем это необходимо. Я честно не могу думать о времени, которое мне когда-либо требовалось создавать элементы управления пользовательского интерфейса в коде и добавлять их в коллекцию Children. Вообще говоря, Windows Phone использует шаблон MVVM, и ваш макет пользовательского интерфейса должен быть выполнен с помощью привязки.

В этом случае, я хотел бы сделать что-то вроде следующего:

public class QuestionModel : INotifyPropertyChanged 
{ 
    private string[] _questions = new string[] 
    { 
     "Question :\n What is OOPS? \n\n Answer: \n Object-oriented programming (OOP) is a programming paradigm based on the concept of objects which are data structures that contain data in the form of fields often known as attributes and code in the form of procedures often known as methods. There are a few principle concepts that form the foundation of object-oriented programming: 1- Object \n 2- Class \n 3- Abstraction \n 4- Polymorphism \n 5- Inheritance \n 6- Encapsulation \n 7- Overloading & OverRiding ", 
     "Question 2", 
     "Question 3", 
     "Question 4" 
    }; 

    private int _selectedIndex = 0; 


    public QuestionModel() { 
     PrevCommand = new DelegateCommand(() => { 
      if(_selectedIndex > 0) { 
       _selectedIndex--; 
       selectedIndexChanged(); 
      } 
     }); 
     NextCommand = new DelegateCommand(() => { 
      if(_selectedIndex < _questions.Length - 1) { 
       _selectedIndex++; 
       selectedIndexChanged(); 
      } 
     }); 
    } 

    private void selectedIndexChanged() { 
     NotifyPropertyChanged("CurrentQuestion"); 
     NotifyPropertyChanged("QuestionText"); 
     NotifyPropertyChanged("IsNextEnabled"); 
     NotifyPropertyChanged("IsPrevEnabled"); 
    } 

    public int CurrentQuestion 
    { 
     get { return _selectedIndex + 1; } 
    } 

    public string QuestionText 
    { 
     get { return _questions[_selectedIndex]; } 
    } 

    public bool IsNextEnabled 
    { 
     get { return _selectedIndex < _questions.Length - 1; } 
    } 

    public bool IsPreviousEnabled 
    { 
     get { return _selectedIndex > 0; } 
    } 

    private ICommand _nextCommand; 
    public ICommand NextCommand 
    { 
     get { return _nextCommand; } 
     set 
     { 
      _nextCommand = value; 
      NotifyPropertyChanged(); 
     } 
    } 

    private ICommand _prevCommand; 
    public ICommand PrevCommand 
    { 
     get { return _prevCommand; } 
     set 
     { 
      _prevCommand = value; 
      NotifyPropertyChanged(); 
     } 
    } 


    public event PropertyChangedEventHandler PropertyChanged; 

    // This method is called by the Set accessor of each property. 
    // The CallerMemberName attribute that is applied to the optional propertyName 
    // parameter causes the property name of the caller to be substituted as an argument. 
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 

public class DelegateCommand : ICommand 
{ 
    private readonly Action _action; 

    public DelegateCommand(Action action) 
    { 
     _action = action; 
    } 

    public void Execute(object parameter) 
    { 
     _action(); 
    } 

    public bool CanExecute(object parameter) 
    { 
     return true; 
    } 

#pragma warning disable 67 
    public event EventHandler CanExecuteChanged; 
#pragma warning restore 67 
} 

Тогда в XAML, я бы следующее:

<Page 
    x:Class="App1.MainPage" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="using:App1" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" 
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
    <Page.DataContext> 
     <local:QuestionModel/> 
    </Page.DataContext> 

    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="*" /> 
      <RowDefinition Height="Auto"/> 
      <RowDefinition Height="Auto" /> 
     </Grid.RowDefinitions> 
     <ScrollViewer VerticalScrollBarVisibility="Auto"> 
      <TextBlock x:Name="Question" Text="{Binding QuestionText}"/> 
     </ScrollViewer> 
     <TextBlock x:Name="Count" Grid.Row="1" Margin="10,10,10,0" Text="{Binding CurrentQuestion, Mode=OneWay}">   
     </TextBlock> 
     <Grid Grid.Row="2"> 
      <Grid.ColumnDefinitions> 
       <ColumnDefinition /> 
       <ColumnDefinition /> 
      </Grid.ColumnDefinitions> 
      <Button x:Name="previous" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="10" Content="Previous" IsEnabled="{Binding IsPreviousEnabled}" Command="{Binding PrevCommand}"></Button> 
      <Button x:Name="next" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="10" Content="Next" IsEnabled="{Binding IsNextEnabled}" Command="{Binding NextCommand}"></Button> 
     </Grid> 
    </Grid> 
</Page> 

Таким образом, нет никакого кода в коде позади, и вам не нужно программно создавать элементы управления или изменять контент. Вы просто позволяете привязке данных к структуре выполнять эту работу за вас, и вашей модели не нужно знать, как пользовательский интерфейс объединяет все и наоборот.

Смежные вопросы