作者:菠萝和尚 | 来源:互联网 | 2023-10-13 14:01
XAML
以上是我的Listbox,它是由以下代码填充的代码:
C#
void GetQueue()
{
var sOngs= new List();
for (int i = 0; i {
songs.Add(new song {
SOngName= MediaPlayer.Queue[i].Name.ToString(),
Album = MediaPlayer.Queue[i].Album.Name.ToString(),
Artist = MediaPlayer.Queue[i].Artist.ToString()
});
}
lsbQueue.ItemsSource = songs.ToList();
//lsbQueue.SelectedValue.ToString();
GlobalVars._sOng= MediaPlayer.Queue.ActiveSongIndex;
lsbQueue.SelectedIndex = GlobalVars._song;
// .......
}
和
public class song
{
public string SongName { get; set; }
public string Album { get; set; }
public string Artist { get; set; }
}
public class Song : List
{
public Song()
{
Add(new song {
SOngName= "",
Album = "",
Artist = ""
});
}
}
我尝试过使用VisualTreeHelper和其他扩展方法,可以在这里找到:
GeekChamp
Falafel Blog
但我没有成功.我几乎放弃了这一点.有没有人有任何想法可以做什么.谢谢.
正如您所看到的 – 我可以成功获取媒体队列,但我想在“SelectedItem”的左侧显示一个视觉提示,就像TextBlock中的播放字符 – tbActive一样.希望这可以帮助!
解决方法:
由于是您尝试访问的DataTemplate中的第一个条目,使用GeekChamp教程中提供的函数.
// namespaces
using System.Windows.Media;
private T FindFirstElementInVisualTree(DependencyObject parentElement) where T : DependencyObject
{
var count = VisualTreeHelper.GetChildrenCount(parentElement);
if (count == 0)
return null;
for (int i = 0; i {
var child = VisualTreeHelper.GetChild(parentElement, i);
if (child != null && child is T)
{
return (T)child;
}
else
{
var result = FindFirstElementInVisualTree(child);
if (result != null)
return result;
}
}
return null;
}
private void lb_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// get the ListBoxItem by SelectedIndex OR index number
//ListBoxItem lbi = (ListBoxItem) this.lb.ItemContainerGenerator.ContainerFromIndex(lb.SelectedIndex);
// get the ListBoxItem by SelectedItem or object in your ViewModel
ListBoxItem lbi = (ListBoxItem)this.lb.ItemContainerGenerator.ContainerFromItem(lb.SelectedItem);
// get your textbox that you want
TextBlock tbActive= FindFirstElementInVisualTree(lbi);
}