Why it is not working?
The XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="218" Width="239">
<Grid>
<ListBox Margin="12" Name="listBox1">
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Name}" Value="Gil">
<Setter Property="ListBoxItem.Background" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox>
</Grid>
</Window>
The Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WpfApplication1
{
public class User
{
private string name;
private string role;
public User(string strName, string strRole)
{
Name = strName;
Role = strRole;
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Role
{
get { return role; }
set { role = value; }
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<User> list = new List<User>();
list.Add(new User("Gil", "Programmer"));
list.Add(new User("Pavel", "Sport"));
list.Add(new User("Max", "Falafel"));
this.listBox1.Items.Clear();
this.listBox1.ItemsSource = list;
}
}
}
Set the ListBoxItem
Style in ListBox.ItemContainerStyle
<ListBox Margin="12" Name="listBox1">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Name}" Value="Gil">
<Setter Property="ListBoxItem.Background" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
You need to define a DataTemplate for the class and set the ItemContainerStyle:
<Window.Resources>
<Style TargetType="{x:Type ListBoxItem}" x:Key="TBStyle">
<Style.Triggers>
<DataTrigger Binding="{Binding Name}" Value="Gil">
<Setter Property="ListBoxItem.Background" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<ListBox Margin="12" Name="listBox1" ItemContainerStyle="{StaticResource TBStyle}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With