I have a GridView
where columns can be bound to numeric values. I use it to switch the style based on a view model value. I.e if it's negative, I want to display red, if it's positive then it should display black, and if it's 0 I don't want to display a value at all.
My problem is with the re-usability of the StyleSelector
public class AmountStyleSelector : StyleSelector
{
public override Style SelectStyle(object item, DependencyObject container)
{
if (!(item is TransactionVm tran))
return null;
var header = ((GridViewBoundColumnBase)((GridViewCellBase)container).Column).Header;
Style Local(decimal value)
{
if (value == 0) return Empty;
return value <= 0 ? Negative : Positive;
}
// OMG what, surely there is a better way,
// other than switch on the column header name?
return header switch
{
"Debit" => Local(tran.Amount.Debit),
"Credit" => Local(tran.Amount.Credit),
"Total" => Local(tran.Amount.Total),
"Balance" => Local(tran.Amount.Balance),
_ => Positive
};
}
public Style Negative { get; set; }
public Style Positive { get; set; }
public Style Empty { get; set; }
}
As you can see, it's hardwired to the column name to pick the view model value (which is actually the bound value).
Is there a way that can work on the actual bound value instead?
Ignoring the visual tree here, it would be nice to be able to do something like this…
var column = ((GridViewBoundColumnBase)((GridViewCellBase)container).Column);
var value = column.BindingProperty.GetActualTrueToGodBoundValue();