2013-11-11 3 views
1

Я использую этот код, чтобы написать TextBlock на страницу Xaml:Написать Xaml TextBlock в C#

Sale.Name = "Price"; 
    Sale.Text = "$200"; 
    deatilLayout.Children.Add(Sale); 
    Grid.SetRow(Sale, 1); 

Это успешно помещает данные на странице XAML, но не в нужном месте.

<FlipView 
      x:Name="flipView" 
      AutomationProperties.AutomationId="ItemsFlipView" 
      AutomationProperties.Name="Item Details" 
      TabIndex="1" 
      Grid.RowSpan="2" 
      ItemsSource="{Binding Source={StaticResource itemsViewSource}}"> 

      <FlipView.ItemContainerStyle> 
       <Style TargetType="FlipViewItem"> 
        <Setter Property="Margin" Value="0,137,0,70"/> 
       </Style> 
      </FlipView.ItemContainerStyle> 

      <FlipView.ItemTemplate> 
       <DataTemplate> 

        <!-- 
         UserControl chosen as the templated item because it supports visual state management 
         Loaded/unloaded events explicitly subscribe to view state updates from the page 
        --> 
        <UserControl Loaded="StartLayoutUpdates" Unloaded="StopLayoutUpdates"> 
         <ScrollViewer x:Name="scrollViewer" Style="{StaticResource HorizontalScrollViewerStyle}" Grid.Row="1"> 

          <!-- Content is allowed to flow across as many columns as needed --> 
          <common:RichTextColumns x:Name="richTextColumns" Margin="117,0,117,47"> 
           <RichTextBlock x:Name="richTextBlock" Width="560" Style="{StaticResource ItemRichTextStyle}" IsTextSelectionEnabled="False"> 

            <Paragraph LineStackingStrategy="MaxHeight" Margin="0,0,0,180"> 
             <InlineUIContainer> 
              <Image x:Name="image" MaxHeight="480" Margin="0,20,0,100" Stretch="Uniform" Source="{Binding Image}" AutomationProperties.Name="{Binding Title}"/> 
             </InlineUIContainer> 
            </Paragraph> 
            <Paragraph Margin="0,0,0,30" LineHeight="65" FontFamily="Global User Interface"> 
             <Run FontSize="52" FontWeight="Thin" Text="{Binding Title}" /> 

            </Paragraph> 
            <Paragraph Margin="0,0,0,50"> 
             <Run Text="TT $" FontSize="24" FontWeight="Thin"/> 
             <Run FontSize="30" FontWeight="Normal" Text="{Binding Subtitle}"/> 


            </Paragraph> 
            <Paragraph x:Name="price" x:FieldModifier="public" /> 
            <Paragraph Margin="0,0,0,40"> 

             <Run FontSize="27" FontWeight="Normal" Text="{Binding Weight}"/> 

            </Paragraph> 
            <Paragraph Margin="0,0,0,40" LineHeight="40"> 

             <Run FontSize="35" FontWeight="Normal" Text="{Binding Description}"/> 

            </Paragraph> 
            <Paragraph Margin="0,0,0,40" LineHeight="30"> 

             <!--<Run FontSize="22" FontWeight="SemiLight" Text="{Binding Category}"/>--> 
            </Paragraph> 
           </RichTextBlock> 

           <!-- Additional columns are created from this template --> 
           <common:RichTextColumns.ColumnTemplate> 
            <DataTemplate> 
             <RichTextBlockOverflow Width="560" Margin="30,0,0,0"> 
              <RichTextBlockOverflow.RenderTransform> 
               <TranslateTransform X="-1" Y="4"/> 
              </RichTextBlockOverflow.RenderTransform> 
             </RichTextBlockOverflow> 
            </DataTemplate> 
           </common:RichTextColumns.ColumnTemplate> 
          </common:RichTextColumns> 

          <VisualStateManager.VisualStateGroups> 

           <!-- Visual states reflect the application's view state inside the FlipView --> 
           <VisualStateGroup x:Name="ApplicationViewStates"> 
            <VisualState x:Name="FullScreenLandscape"/> 
            <VisualState x:Name="Filled"/> 

            <!-- Respect the narrower 100-pixel margin convention for portrait --> 
            <VisualState x:Name="FullScreenPortrait"> 
             <Storyboard> 
              <ObjectAnimationUsingKeyFrames Storyboard.TargetName="richTextColumns" Storyboard.TargetProperty="Margin"> 
               <DiscreteObjectKeyFrame KeyTime="0" Value="97,0,87,57"/> 
              </ObjectAnimationUsingKeyFrames> 
              <ObjectAnimationUsingKeyFrames Storyboard.TargetName="image" Storyboard.TargetProperty="MaxHeight"> 
               <DiscreteObjectKeyFrame KeyTime="0" Value="400"/> 
              </ObjectAnimationUsingKeyFrames> 
             </Storyboard> 
            </VisualState> 

            <!-- When snapped, the content is reformatted and scrolls vertically --> 
            <VisualState x:Name="Snapped"> 
             <Storyboard> 
              <ObjectAnimationUsingKeyFrames Storyboard.TargetName="richTextColumns" Storyboard.TargetProperty="Margin"> 
               <DiscreteObjectKeyFrame KeyTime="0" Value="17,0,17,57"/> 
              </ObjectAnimationUsingKeyFrames> 
              <ObjectAnimationUsingKeyFrames Storyboard.TargetName="scrollViewer" Storyboard.TargetProperty="Style"> 
               <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource VerticalScrollViewerStyle}"/> 
              </ObjectAnimationUsingKeyFrames> 
              <ObjectAnimationUsingKeyFrames Storyboard.TargetName="richTextBlock" Storyboard.TargetProperty="Width"> 
               <DiscreteObjectKeyFrame KeyTime="0" Value="280"/> 
              </ObjectAnimationUsingKeyFrames> 
              <ObjectAnimationUsingKeyFrames Storyboard.TargetName="image" Storyboard.TargetProperty="MaxHeight"> 
               <DiscreteObjectKeyFrame KeyTime="0" Value="160"/> 
              </ObjectAnimationUsingKeyFrames> 
             </Storyboard> 
            </VisualState> 
           </VisualStateGroup> 
          </VisualStateManager.VisualStateGroups> 
         </ScrollViewer> 
        </UserControl> 
       </DataTemplate> 
      </FlipView.ItemTemplate> 
     </FlipView> 

Я хотел бы поместить данные в пункте в RichTextBlock, который находится в Grid «detailLayout».

Как это сделать?

ответ

0

почему бы вам не место Grid.Column = "" и Grid.Row = ""

<Paragraph Grid.Column="0" and Grid.Row="0"> 
</Paragraph> 
0

Я хотел бы призвать вас использовать MVVM и попробовать это:

<RichTextBlock FontSize="12" FontFamily="Segoe UI" > 
           <Paragraph > 
            <Run Text="{Binding Sale.Text}"/> <Run Text="{Binding Sale.Text }"/> 
           </Paragraph> 
          </RichTextBlock> 

Если вы не используют MVVM, вам придется создать объект «Запустить», вставить текст и добавить его в chilrends RichTextBlock.

1

Один из способов сделать это является, в файле XAML, изменить Paragraph элемент к следующему:

<Paragraph x:Name="price" /> 

Это делает экземпляр абзаца видимую отделенного кода в поле под названием " цена". Затем, в качестве примера, вы можете получить доступ и установить содержание этого пункт instancein кода-за, используя следующий код:

string textToSet = "Price: $200"; // Replace this value with whatever value you want to 
            // set in the paragraph. 
Run textRun = new Run(); 
textRun.Text = textToSet;  
this.price.Inlines.Add(textRun); 

Затем, если вы хотите, чтобы очистить содержимое экземпляра Paragraph, вы можете сделать Ниже в отделенном коде:

this.price.Inlines.Clear(); 

по умолчанию при присвоении имени элемента на странице XAML, то этот элемент не является общедоступным для внешнего кода. Если необходимо получить доступ к «цене» Paragraph элемент из внешней страницы XAML в коде-позади, вам нужно будет изменить декларацию абзаца элемента к следующему:

<Paragraph x:Name="price" x:FieldModifier="public" /> 

Последнее, что следует отметить, что вы не могут обращаться к именованным элементам, если они находятся в DataTemplate (обычно используется с элементами элементов WPF). Поэтому, если это так, вы можете захотеть использовать подход MVVM.

+0

Код не распознает 'price' – Tester

+0

Я внес изменения для дальнейшего уточнения того, что необходимо сделать, чтобы элемент« цена »был доступен из-за пределов вашей страницы XAML. Хотя я не уверен, что это исправит вашу проблему, поскольку я не видел, где ваш код C# находится по размеру относительно вашей страницы XAML. – pixelTitan

+0

Я до сих пор получаю сообщение об ошибке «Ошибка « BG.ItemDetailPage »не содержит определения для« цены », а метод расширения« цена », принимающий первый аргумент типа« BG.ItemDetailPage », может быть найден (вы отсутствуете директива using или ссылка на сборку?) \t 'C# - файл для страницы Xaml. Эта страница Xaml является ItemDetailPage.xaml, а файл с кодом C# - ItemDetailPage.xaml.cs – Tester

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