简体   繁体   English

以编程方式从Windows Phone 8.1 XAML中的ListView中的特定ListViewItem到达TextBlock

[英]Reach a TextBlock from a specific ListViewItem from the ListView in Windows Phone 8.1 XAML programmatically

I am a new developer on Windows Phone 8.1, I am try to reach a specific ListView item from the ListView collection and be able to color it or color the TextBock inside of it, But I can't reach the item or reach any of items inside of ListView, Please take a look for my below code : 我是Windows Phone 8.1的新开发人员,我尝试从ListView集合中获取特定的ListView项目,并能够为其内部的TextBock着色或着色,但我无法访问该项目或达到任何项目在ListView内部,请查看我的以下代码:

    protected async override void OnNavigatedTo(NavigationEventArgs e)
    {
                   SQLiteRT db1 = new SQLiteRT();
            var db_connection = await db1.Connection("MyDB.sqlite");

            List<MyTBL> t_list = db1.GetTable("SELECT * FROM MyTBL LIMIT 4 ORDER BY RANDOM() ;");
            db_connection.Close();

          LV_Options.ItemsSource = t_list;
    }
 // my List View called LV_Options
private void LV_Options_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
     ListView lv1 = sender as ListView;
     if (lv1 == null)
          return;

     MyTBL wrd = lv1.SelectedItem as MyTBL;
     if (wrd == null)
         return;

     TextBlock tb = lv1.FindName("TB_AMean1") as TextBlock;
     tb.FontSize = 17; // here I got debug error (it not worked !!!!!!!)

     var item =  LV_Options.Items.ElementAt(3); // this seems not work also !!!!
     item.BackColor = Color.LightSteelBlue; 

}

As you can see above, I tried to reach a specific item by LV_Options.Items.ElementAt(3) but it doesn't work! 正如您在上面所看到的,我尝试通过LV_Options.Items.ElementAt(3)来访问特定项目,但它不起作用! I also tried to reach the TextBlock from the selected List view item, but also not worked ! 我还试图从选定的列表视图项目到达TextBlock,但也没有工作!

(Updated) XAML code : (更新)XAML代码:

<!-- Title Panel -->
        <StackPanel Grid.Row="0" Margin="19,0,0,0">
            <TextBlock Name="TB_Rslt" Text="Here result of your answer" Style="{ThemeResource TitleTextBlockStyle}" Margin="0,12,0,0"/>
            <TextBlock Text="page title" Margin="0,-6.5,0,26.5" Style="{ThemeResource HeaderTextBlockStyle}" CharacterSpacing="{ThemeResource PivotHeaderItemCharacterSpacing}"/>
        </StackPanel>

        <!--TODO: Content should be placed within the following grid-->
        <Grid Grid.Row="1" x:Name="ContentRoot" Margin="19,10,19,15">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <TextBlock Name="TB_Question" Text="Choose Answer " Margin="0,0,25,0" HorizontalAlignment="Right" FontWeight="Bold" FontSize="22" FontFamily="Verdana" RenderTransformOrigin="0.5,0.5" />
            <TextBlock Name="TB_EnWord" Text="" Margin="90,0,15,0" HorizontalAlignment="Left" FontWeight="Bold" FontSize="22" FontFamily="Verdana" RenderTransformOrigin="0.5,0.5" TextAlignment="Right" />
            <StackPanel Grid.Row="1" Margin="5,22,0,0">
                <ListView Name="LV_Options" SelectionChanged="LV_Options_SelectionChanged">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <Grid Margin="6">
                       <StackPanel VerticalAlignment="Top" Margin="10,0,0,0">
                 <TextBlock Name="TB_AMean1" Text="{Binding AMean1}" TextWrapping="Wrap"/>
                                </StackPanel>
                            </Grid>
                        </DataTemplate>
                    </ListView.ItemTemplate>

                </ListView>
            </StackPanel>
            <Button Name="Btn_Answer" Content="Ansewr" HorizontalAlignment="Left" Grid.Row="1" VerticalAlignment="Bottom" Click="Btn_Answer_Click"/>

My application is a quiz application that offer 4 choices/options as answers for each question, and when user select a true answer, I want to highlight the true answer(true choice) by make its background to green, and if the user selected wrong answer/option I want to make the background of that answer (a specific List View item) with red. 我的应用程序是一个测验应用程序,提供4个选项/选项作为每个问题的答案,当用户选择真正的答案时,我想突出显示真正的答案(真正的选择),使其背景为绿色,如果用户选择了错误回答/选项我想用红色表示该答案的背景(一个特定的列表视图项)。

Any help please ? 有什么帮助吗?

You're not going to be able to access an element inside a data template like that. 您无法像这样访问数据模板中的元素。 Instead, leverage the binding to a view model to set the color and other view-related properties. 相反,利用绑定到视图模型来设置颜色和其他与视图相关的属性。 First, create a wrapper view model for your data class: 首先,为您的数据类创建一个包装器视图模型:

public class MyTBLViewModel : INotifyPropertyChanged
{
    public MyTBL Entity
    {
        get { return _entity; }
    }
    private readonly MyTBL _entity;

    public Brush Highlight
    {
        get { return _brush; }
        set
        {
            _brush = value;
            RaisePropertyChanged("Highlight");
        }
    }
    private Brush _highlight;

    public double ItemFontSize
    {
        get { return _itemFontSize; }
        set
        {
            _itemFontSize = value;
            RaisePropertyChanged("ItemFontSize");
        }
    }
    private Brush _itemFontSize;

    public MyTBLViewModel(MyTBL entity)
    {
        _entity = entity;
        _highlight = new SolidColorBrush(Colors.Transparent);
        _itemFontSize = 12;
    }

    public event PropertyChangedEventArgs PropertyChanged;

    protected void RaisePropertyChanged(string propName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propName));
    }
}

Use this as your ItemsSource : 将此作为ItemsSource

List<MyTBLViewModel> t_list = db1.GetTable("SELECT * FROM MyTBL LIMIT 4 ORDER BY RANDOM() ;")
    .AsEnumerable().Select(entity => new MyTBLViewModel(entity)).ToList();

Now in your view, bind the view elements to "Highlight" and "ItemFontSize", and to any other properties you like: 现在在您的视图中,将视图元素绑定到“Highlight”和“ItemFontSize”,以及您喜欢的任何其他属性:

<ListView.ItemTemplate>
    <DataTemplate>
        <Grid Margin="6" Background="{Binding Highlight}">
            <StackPanel VerticalAlignment="Top" Margin="10,0,0,0">
                <TextBlock Name="TB_AMean1" Text="{Binding Entity.AMean1}" TextWrapping="Wrap" 
                           FontSize="{Binding ItemFontSize}"/>
            </StackPanel>
        </Grid>
    </DataTemplate>
</ListView.ItemTemplate>

Finally, you can get the data item from the SelectionChangedEventArgs -- use it to update your view-related properties: 最后,您可以从SelectionChangedEventArgs获取数据项 - 使用它来更新与视图相关的属性:

private void LV_Options_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    foreach (var item in e.AddedItems.OfType<MyTBLViewModel>())
    {
        item.Highlight = new SolidColorBrush(Color.LightSteelBlue);
        item.ItemFontSize = 17;
    }

    foreach (var item in e.RemovedItems.OfType<MyTBLViewModel>())
    {
        item.Highlight = new SolidColorBrush(Colors.Transparent);
        item.ItemFontSize = 12;
    }
}
var item =  LV_Options.Items.ElementAt(3);

This line is incorrect. 这条线不正确。 It will not return you a TextBlock . 它不会返回TextBlock I don't know what a .BackColor is, and it should not compile. 我不知道.BackColor是什么,它不应该编译。 The Items property in a ListView will return you a list of ListViewItems . ListView的Items属性将返回ListViewItems列表。 If you want to access the inside element from a ListViewItem , you'll need to access the ContentTemplateRoot property. 如果要从ListViewItem访问inside元素,则需要访问ContentTemplateRoot属性。

Do not use var ever. 不要使用var It lets you assume that you know the type, whereas if you explicitly typed the declaration you would realize you're doing it wrong. 它让你假设你知道类型,而如果你明确地输入了声明,你会发现你做错了。

 MyTBL wrd = lv1.SelectedItem as MyTBL;
 if (wrd == null)
     return;

 TextBlock tb = lv1.FindName("TB_AMean1") as TextBlock;

What is a MyTBL type? 什么是MyTBL类型? FindName is only available to framework DependencyObjects so I'm assuming it's a user control? FindName仅适用于框架DependencyObjects所以我假设它是一个用户控件? You have to provide a lot more code to show us what you're doing and what you're setting the ListView's ItemsSource and ItemTemplate with and what these errors are and how you have 2 breaking debug errors at once and what the error messages are. 您必须提供更多代码来向我们展示您正在做什么以及您正在设置ListView's ItemsSourceItemTemplate以及这些错误是什么以及如何一次性破解调试错误以及错误消息是什么。

Comprehending runtime error messages is a huge part of being a good developer. 理解运行时错误消息是成为优秀开发人员的重要组成部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM