Make sure your type implements the INotifyPropertyChanged interface and you fire the change notification on the setter of your publicly exposed property which the DataTrigger
is bound to when you modify the color.
EDIT: Below is an example using a TextBox
and a Button
to change the color...
C#:
public partial class Window1 : Window
{
MyData _data = new MyData();
public Window1()
{
InitializeComponent();
this.DataContext = _data;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
_data.ChangeColor();
}
}
public class MyData : INotifyPropertyChanged
{
Random _rand = new Random();
List<String> _colors = new List<string> { "Red", "Black", "Blue" };
public void ChangeColor()
{
MyColor = _colors[_rand.Next(0, 3)];
}
private bool _isActive = true;
public bool IsActive
{
get
{
return _isActive;
}
set
{
_isActive = value;
PropertyChangedEventHandler h = PropertyChanged;
if (h != null)
h(this, new PropertyChangedEventArgs("IsActive"));
}
}
private String _myColor = "Green";
public String MyColor
{
get
{
return _myColor;
}
set
{
_myColor = value;
PropertyChangedEventHandler h = PropertyChanged;
if (h != null)
h(this, new PropertyChangedEventArgs("MyColor"));
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
}
XAML:
<Grid>
<Button Height="25" Click="Button_Click" Content="Change Color" VerticalAlignment="Bottom" />
<TextBox Width="200" Height="100">
<TextBox.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding IsActive}" Value="true">
<Setter Property="TextBox.Background" Value="{Binding MyColor}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</Grid>