Reputation: 3065
Im quite new to the WPF, so this may be a simple question.
I have ListBox with with defined style, font and whole rest of the stuff. I want to highlight one row there, but the problem is that all rows are added programatically, so I can't just edit the row properties and change for example foreground collor (that would be enough). I know the target row ID, but I can't find any way to access its ListItemBox object. To access the specific item I used:
((MyClass)(Playlist.Items[i])).MyProperty = 0; //Access the i element of ListBox named Playlist
Is it even possible? I searched for the solutions here and on other sites, but nothing helps in my case.
Thanks for any help.
EDIT: I don't mean to select the row, but to change it's foreground color.
Upvotes: 0
Views: 958
Reputation: 911
Design The listbox control template from SCRATCH using Blend it will help you to change foreground color of selected item in listbox. Also Blend is wonderful tool for WPF UI designs so check it.
Upvotes: 0
Reputation: 12811
If you can't implement a proper MVVM solution for this, you can get the ListBoxItem
s from the Items
property of the ListBox
. If the ListBox
is data bound (using the ItemsSource
property), each of the ListBoxItem
s that is automatically generated will have its DataContext
property set to an item in the collection that is bound to the ItemsSource
property. You can evaluate it there. I wouldn't recommend this approach, however. Use a proper MVVM solution if possible.
var id = ...;
var item = (from ListBoxItem i in ListBox1.Items
let data = (MyClass) i.DataContext
where data.Id == id
select i).FirstOrDefault();
if (item != null)
item.Foreground = Brushes.Red;
Upvotes: 0
Reputation: 808
You could use a DataTemplate and a DataTrigger. Your DataTemplate defines what you want each item in your listbox to look like (TextBlock, Image, etc). The DataTrigger will flag specific data conditions on each item in your list box and change the style of DataTemplate accordingly (like Foreground color). This is assuming your ListBox is databound to a collection of MyClass with a property named MyProperty.
<DataTemplate>
<TextBlock Text="{Binding MyProperty}"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=ID}">
<DataTrigger.Value>
303216
</DataTrigger.Value>
<DataTrigger.Setters>
<Setter Property="Foreground" Value="Navy"/>
</DataTrigger.Setters>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
http://msdn.microsoft.com/en-us/library/system.windows.datatemplate.triggers.aspx
Upvotes: 2