这是我为这个问题想出的,作为 LS 2015 的更通用的解决方案。
假设:我有一个名为 MySpecialConfigurationGrid 的数据网格
假设:MySpecialConfigurationGrid 的底层 EF 类型是 MySpecialConfiguration
给定:我要着色并用作颜色信息源的列单元称为 MyColor
Given:此代码进入 LSML 背后的代码。
void proxy_ControlAvailable(object sender, ControlAvailableEventArgs e)
{
var ctrl = (DataGrid)e.Control;
ctrl.LoadingRow += new EventHandler<DataGridRowEventArgs>(Ctrl_LoadingRow);
}
private void Ctrl_LoadingRow(object sender, DataGridRowEventArgs e)
{
//Getting a particular cell is tricky,
// you have cross reference the row instance in the particular
// column you want to find, and then get that thing's parent,
// which happens to be the DataGridCell you can control the rendering of.
DataGrid grid = (DataGrid)sender;
DataGridRow row = new DataGridRow();
row = e.Row;
var cell = (grid.Columns.First(item => item.SortMemberPath == nameof(MySpecialConfiguration.MyColor))
.GetCellContent(row) as Microsoft.LightSwitch.Presentation.Framework.ContentItemPresenter)
.Parent as DataGridCell;
Binding bgbinding = new Binding(nameof(MySpecialConfiguration.MyColor))
{
Mode = BindingMode.TwoWay,
Converter = new RowColorConverter(),
ValidatesOnExceptions = true
};
cell.SetBinding(DataGridCell.BackgroundProperty, bgbinding);
}
partial void MySpecialConfiguration_InitializeDataWorkspace(global::System.Collections.Generic.List<global::Microsoft.LightSwitch.IDataService> saveChangesTo)
{
Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke(() =>
{
var proxy = this.FindControl(nameof(MySpecialConfigurationGrid));
proxy.ControlAvailable += new EventHandler<ControlAvailableEventArgs>(proxy_ControlAvailable);
});
}
public class RowColorConverter : IValueConverter
{
public RowColorConverter() { }
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null)
{
var match = Regex.Match(value as string, "#(?<R>[a-fA-F0-9]{2})(?<G>[a-fA-F0-9]{2})(?<B>[a-fA-F0-9]{2})");
if (match.Success)
{
return new System.Windows.Media.SolidColorBrush(Color.FromArgb(255,
sToB(match.Groups["R"].Value),
sToB(match.Groups["G"].Value),
sToB(match.Groups["B"].Value)));
}
}
return new System.Windows.Media.SolidColorBrush(Color.FromArgb(0, 255, 255, 255));
}
private byte sToB(string s)
{
return byte.Parse(s, System.Globalization.NumberStyles.HexNumber);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
基本上,它的工作方式是将事件附加到行的创建,然后绑定到行的加载事件。从那里,您可以访问数据网格本身及其可视化树。做一些技巧来获取对 DataGridCell 的引用,然后将具有 IValueConverter 的绑定添加到其背景依赖项属性。 IValueConverter 将 HTML 十六进制颜色三元组字符串解析为组件部分,并从中返回 SolidColorBrush。
对于您的特定 Gender_Man = true 事物,调整 ValueConverter 以接受适当的值,并更改代码其他位中的 nameof() 调用以引用适当的列进行绑定(绑定附加到颜色列) ,以及用于查找要着色的目标列的单元格。