Reputation: 9702
I am trying to change the foreground color of a text block based on a bool property that its value is changed when a button is clicked. However, for some reason this is not working. Also, do I have to add the bool property to a list in first place? I tried adding the bool property directly to the DataContext, but this did not work either. Any help would be appreciated.
public static bool IsOn { get; set; }
public static List<bool> boo;
private void Button_Click(object sender, RoutedEventArgs e)
{
IsOn = true;
boo = new List<bool>();
boo.Add(IsOn);
DataContext = boo;
}
<Window.Resources>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="Green" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsOn}" Value="true">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<StackPanel>
<Button Click="Button_Click" Content="Change Color" />
<TextBlock Name="textBlockColor" Text="My Foreground Color" />
</StackPanel>
Upvotes: 2
Views: 3047
Reputation: 19296
First of all your class must implement INotifyPropertyChanged
(msdn) to notify view that your property was changed.
Second you must assign DataContext
in MainWindow
constructor.
Example:
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
private bool _isOn;
public bool IsOn
{
get { return _isOn; }
set { _isOn = value; OnPropertyChanged("IsOn"); }
}
private void Button_Click(object sender, RoutedEventArgs e)
{
IsOn = !IsOn;
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propName));
}
}
Your XAML code is OK.
When your binding doesn't work you should use snoop in the future.
Upvotes: 4