我在数据网格中有一个内容为True / false的列,如何根据文本将此true / false(boolean)更改为图像?
我正在使用c#wpf。
编辑:
<dg:DataGridTemplateColumn MinWidth="70" Header=" Is Done2">
<dg:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Name="imgIsDone" Source="../Resources/Activo.png"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=IsDone}" Value="False">
<Setter TargetName="imgIsDone" Property="Source" Value="../Resources/Inactivo.png"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</dg:DataGridTemplateColumn.CellTemplate>
</dg:DataGridTemplateColumn>
答案 0 :(得分:12)
public class BoolToImage : IValueConverter
{
public Image TrueImage { get; set; }
public Image FalseImage { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (!(value is bool))
{
return null;
}
bool b = (bool)value;
if (b)
{
return this.TrueImage;
}
else
{
return this.FalseImage;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
然后在您的xaml中,作为资源:
<local:BoolToImage TrueImage="{StaticResource Image}" FalseImage="{StaticResource FalseImage}" x:Key="BoolImageConverter"/>
然后在你的装订中:
ImageSource={Binding Path=BoolProp,Converter={StaticResource BoolImageConverter}}"
答案 1 :(得分:10)
使用DataGridTemplateColumn为包含Image的列提供DataTemplate,并使用值转换器或数据触发器根据列的值设置图像源。以下是使用数据触发器的示例:
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Name="MyImage" Source="TrueImage.png"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding BoolColumn}" Value="False">
<Setter TargetName="MyImage" Property="Source" Value="FalseImage.png"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
答案 2 :(得分:0)
万一有人想从benPearce那里获得答案,我不得不修改转换器以使用ImageSource!
using System;
using System.Windows.Data;
using System.Windows.Media;
namespace ViewManager
{
public class BoolToImageConverter : IValueConverter
{
public ImageSource TrueImage { get; set; }
public ImageSource FalseImage { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (!(value is bool))
{
return null;
}
bool b = (bool)value;
if (b)
{
return this.TrueImage;
}
else
{
return this.FalseImage;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
使用资源
<local:BoolToImageConverter x:Key="BoolToImageConverter" FalseImage="{StaticResource UnLockedSource}" TrueImage="{StaticResource LockedSource}" />
...
<Button Grid.Column="2" Command="{Binding LockUnlockCommand}" >
<Image Source="{Binding IsLocked, Converter={StaticResource BoolToImageConverter}}" MinHeight="50" MinWidth="50" />
</Button>