我有一个清单:
姓名年龄描述
我需要在网格中显示。
如何在Grid中显示Description的绑定属性,如果描述中包含特定关键字“Good”,“Kind”,那么必须以这样的方式突出显示“Good”它必须是粉红色并且“Kind”它必须是红色的。
例
姓名年龄描述
ABC 25我很善良
XYZ 28我是一个善良的人
PQR 26我是一个快乐的人。
我需要使用这个MVVM
模型:
private string name
public string Name { get { return name } set { name = value; } }
private int age
public int Age{ get { return age} set { age= value; } }
private string description
public string Description{ get { return description} set { description= value; } }
在Xaml: -
<TextBlock Name="tbDescription" Text="{Binding RowData.Row.Description, Mode=OneWay}"
Width="300" VerticalAlignment="Center" HorizontalAlignment="Left" TextTrimming="CharacterEllipsis" MinWidth="300">
您可以使用ValueConverter
根据字符串返回所需的颜色。
public class ForeGroundColorConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
var color = (string)value;
if(color.IndexOf("good", StringComparison.OrdinalIgnoreCase) >= 0)
{
// return 'Good' color.
}
else if (color.IndexOf("kind", StringComparison.OrdinalIgnoreCase) >= 0)
{
// return 'Kind' color.
}
// More cases.
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
然后在绑定中使用此转换器。 (应用于您需要的控件。我以TextBlock为例。)
<TextBlock Name="Your text."
ForeGround={Binding Description, Converter={StaticResource ForeGroundColorConverter}/>
首先将其添加到XML命名空间:
xmlns:converters="clr-namespace:<YourNameSpace>"
您还需要向窗口/控件添加资源。
<Window.Resources>
<converters.ForeGroundColorConverter x:Key="ForeGroundColorConverter"/>
</Window.Resources>