I'm trying to add a new trigger to a custom control in WPF programmatically by adding a new style. Control inherits from ToggleButton, and trigger should rely on IsCheckedProperty of the button. Even though I specifically assign value to IsChecked, InvalidOperationException is still thrown. Snippet:
protected BalanceSheetButton(OperationSummaryModel summaryModel, OperationFlow operationFlow,
StackPanel mainPanel)
{
this.IsChecked = true;
RegisterStyle();
}
private void RegisterStyle()
{
var a = ((DependencyObject)this).ReadLocalValue(IsCheckedProperty);
var style = new Style();
var trigger = new Trigger();
trigger.Property = IsCheckedProperty;
trigger.Setters.Add(new Setter { Property = ForegroundProperty, Value = this.Foreground });
style.Triggers.Add(trigger);
Style = style;
}
The exception: '{DependencyProperty.UnsetValue}' is not a valid value for property 'IsChecked'.
this.ReadLocalValue(IsCheckedProperty) returns assigned value, so why would it complain about the UnsetValue?
I tried assigning a value to IsChecked specifically to no avail. Both this.GetValue(IsCheckedProperty) and this.ReadLocalValue(IsCheckedProperty) return the assigned value.
You forgot to specify the value for the trigger. Just add
trigger.Value = true;
the UnsetValue
in the message was the default value for trigger.Value
.