1

尽管这听起来很愚蠢,但我对此感到有些困惑。这是我在 Win Phone 8 应用程序中的 XAML:

<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <!--TitlePanel contains the name of the application and page title-->
    <StackPanel Grid.Row="0" Margin="12,17,0,28">
        <TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
        <TextBlock Text="Page" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
    </StackPanel>

    <!--ContentPanel - place additional content here-->

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <phone:LongListSelector x:Name="MainLongListSelector" Margin="0,0,-12,0" ItemsSource="{Binding Items}" SelectionChanged="MainLongListSelector_SelectionChanged">
            <phone:LongListSelector.ItemTemplate>
                <DataTemplate>
                    <StackPanel Margin="0,0,0,17">
                        <TextBlock x:Name="TextBlock1" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top"/>
                    </StackPanel>
                </DataTemplate>
            </phone:LongListSelector.ItemTemplate>
        </phone:LongListSelector>
    </Grid>
</Grid>

我四处搜索,但我不知道为什么我不能在后面的代码中针对 TextBlock1 控件编写代码。当我输入 TextBlock1.Text= .... 我收到错误TextBlock1 is not declared 。由于其保护级别,它可能无法访问。 但是我看不到它是如何私密的?

我要做的就是添加一个文本块,为其分配一些内容,然后将所选值传递到另一个页面以执行相关操作。

此外,只要我将它从 PhoneListSelector 中删除,我就可以访问它。

4

1 回答 1

3

TextBlock1在 ItemTemplate中定义,任何定义为 Template 的内容都不能直接访问,因为它将由控件在运行时创建。

如果您想操作 LongListSelector 的 DataContext 所具有的任何内容,您可能需要对 TextBlock 进行绑定。

<phone:LongListSelector x:Name="MainLongListSelector" Margin="0,0,-12,0" ItemsSource="{Binding Items}" SelectionChanged="MainLongListSelector_SelectionChanged">
        <phone:LongListSelector.ItemTemplate>
            <DataTemplate>
                <StackPanel Margin="0,0,0,17">
                    <TextBlock x:Name="TextBlock1" Text="{Binding Content"} HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top"/>
                </StackPanel>
            </DataTemplate>
        </phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
MainLongListSelector.DataContext = new List<TestViewModel>();

public class TestViewModel : INotifyPropertyChanged
{
 //Assuming you've implemented the interface
  private string _content;
  public string Content { get { return _content; } { set { _content = value; NotifyOfPropertyChanged("Content"); } }
}

从这里,您可以尝试访问选定的值内容并将其传递到下一页。

var selectedItem = MainLongListSelector.SelectedItem as TestViewModel;
GoToNextPage(selectedItem.Content);

我强烈建议阅读 MVVM 设计模式,一切都应该很容易实现,永远记住UI 不是 DATA它的责任只是显示通过 ViewModel 传递的东西。

于 2013-09-12T18:05:32.483 回答