我有一个
GridView
其中列可以绑定到数值。我使用它来根据视图模型值切换样式。也就是说,如果它是负的,我想显示红色,如果是正的,那么它应该显示黑色,如果是0,我根本不想显示值。
我的问题在于
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; }
}
如您所见,它与列名硬连线以选择视图模型值(实际上是绑定值)。
有没有一种方法可以处理实际的绑定值?
忽略这里的视觉树,能够做这样的事情会很好…
var column = ((GridViewBoundColumnBase)((GridViewCellBase)container).Column);
var value = column.BindingProperty.GetActualTrueToGodBoundValue();