如何从选定的ListViewItem获取TextBlock控件 [英] How to get TextBlock control from selected ListViewItem

查看:104
本文介绍了如何从选定的ListViewItem获取TextBlock控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为UWP应用构建音乐播放器。我需要更改歌曲ListView的ListViewItem中文本块的前景。因此,每当用户从列表中选择任何项目时,文本块的前景应该改变以指示用户该项目当前正在播放
。 

I am building a Music Player for UWP app. I need to change the foreground of a textblock in the ListViewItem of the Songs' ListView. So that whenever the user selects any item from the list, the textblock's foreground should change to indicate the user that the item is currently playing. 

这是XAML代码对于项目Templete。如果你可以在Item Selected事件中用C#为我编写代码。

Here is the XAML code for the Item Templete. If you can then write the code for me in C# in the Item Selected event.

<ListView Name="SongsListView"
                                  IsItemClickEnabled="True"
                                  ItemClick="SongsListView_ItemClick"
                              ItemsSource="{x:Bind rootpage.Songs}"
                          VerticalAlignment="Top" 
                          HorizontalAlignment="Stretch">
                            <ListView.ItemTemplate>
                                <DataTemplate x:DataType="model:Song">
                                    <controls:DropShadowPanel ShadowOpacity="0.20"
                                              Color="Black"
                                              HorizontalContentAlignment="Stretch"
                                              BlurRadius="10"
                                              OffsetX="0"
                                              OffsetY="7.0">
                                        <Grid HorizontalAlignment="Stretch" CornerRadius="5" Background="{ThemeResource SystemControlAltHighAcrylicElementBrush}">
                                            <StackPanel Orientation="Horizontal">
                                                <TextBlock Text="{x:Bind Name}" Name="songNameTextBlock" TextWrapping="Wrap"/>
                                                <TextBlock Text="{x:Bind Artist}" Name="ArtistNameTextBlock" TextWrapping="Wrap"/>
                                            </StackPanel>
                                        </Grid>
                                    </controls:DropShadowPanel>
                                </DataTemplate>
                            </ListView.ItemTemplate>
                            <ListView.ItemContainerStyle>
                                <Style TargetType="ListViewItem">
                                    <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                                    <Setter Property="VerticalContentAlignment" Value="Stretch"/>
                                    <Setter Property="Margin" Value="4"/>
                                </Style>
                            </ListView.ItemContainerStyle>
                        </ListView>


        private void SongsListView_ItemClick(object sender, ItemClickEventArgs e)
        {
//Write the code, Please             
        }

推荐答案

您好SHAKIR820,

Hi SHAKIR820,

您可以使用数据绑定通过将项目文本块的前景绑定到数据来更改所选文本块的前景source的属性,这是一个例子。

You can use the data binding to change the Foreground of the selected textblock by binding the items textblock's foreground to a data source's property, here is an example.

在Xaml中,

       <ListView x:Name="forecolorList" Margin="0,0,0,10" IsItemClickEnabled="True" ItemClick="StudentsList_ItemClick">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="local:Listviewobject" >
                    <StackPanel>
                       <TextBlock Text="{x:Bind  ShowButtonText}" 
                           Margin="20,0,20,8"
                           FontSize="24" 
                           FontStyle="Italic" 
                           FontWeight="SemiBold"
                           Foreground="{x:Bind Forecolor ,Mode=OneWay}" />
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

在后面的代码中:

public sealed partial class Listviewxbind : Page
    {
        ObservableCollection<Listviewobject> obsinfo = new ObservableCollection<Listviewobject>();
        public Listviewxbind()
        {
            this.InitializeComponent();
            obsinfo.Add( new Listviewobject() { ShowButtonText="testshow1" , Forecolor= new SolidColorBrush(Colors.Blue) });
            obsinfo.Add(new Listviewobject() { ShowButtonText = "wuxiwo", Forecolor = new SolidColorBrush(Colors.BurlyWood) });
            forecolorList.ItemsSource = obsinfo;
        }

        private void StudentsList_ItemClick(object sender, ItemClickEventArgs e)
        {
            Listviewobject lvob = (Listviewobject)e.ClickedItem;
            lvob.Forecolor = new SolidColorBrush(Colors.Red);
        }
    }

    public class Listviewobject : INotifyPropertyChanged
    {
        public Listviewobject()
        {
        }

        private string showButtonText;
        public string ShowButtonText
        {
            get { return this.showButtonText; }
            set
            {
                this.showButtonText = value;
                this.OnPropertyChanged();
            }
        }

        private SolidColorBrush forecolor;
        public SolidColorBrush Forecolor
        {
            get { return this.forecolor; }
            set
            {
                this.forecolor = value;
                this.OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged = delegate { };
        public void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            // Raise the PropertyChanged event, passing the name of the property whose value has changed.
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

此外,您还可以尝试使用  VisualTreeHelper 获取Textblock并设置其前景。与上述第一种情况相比,不推荐使用

Besides, You can also try to use the  VisualTreeHelper to get the Textblock and set its foreground. Compared with above first scenario, this is not recommended.

以下代码可以从可视化树中获取特定类型的子元素列表。它使用基本遍历方法GetChildrenCount和GetChild。


The following code can get a list of child elements of a particular type from within a visual tree. It uses the basic traversal methods GetChildrenCount and GetChild.

public  void FindChildren<T>(List<T> results, DependencyObject startNode)
  where T : DependencyObject
        {
            int count = VisualTreeHelper.GetChildrenCount(startNode);
            for (int i = 0; i < count; i++)
            {
                DependencyObject current = VisualTreeHelper.GetChild(startNode, i);
                if ((current.GetType()).Equals(typeof(T)) || (current.GetType().GetTypeInfo().IsSubclassOf(typeof(T))))
                {
                    T asType = (T)current;
                    results.Add(asType);
                }
                FindChildren<T>(results, current);
            }
        }

然后,您可以在SongsListView_ItemClick事件中使用以下代码。

Then, you can use the following code in the SongsListView_ItemClick event.

     private void SongsListView_ItemClick(object sender, ItemClickEventArgs e)
        {
            var prevItem = SongsListView.ContainerFromItem(e.ClickedItem) as ListViewItem;
            List<TextBlock> listblock = new List<TextBlock>();
            FindChildren(listblock, prevItem);
            foreach (var txbl in listblock)
            {
                if(txbl.Name== "songNameTextBlock")
                {
                    txbl.Foreground = new SolidColorBrush(Windows.UI.Colors.Red);
                }
            }
        }

最好的问候,

Yong Lu


这篇关于如何从选定的ListViewItem获取TextBlock控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆