基于数据模板中的布尔值的图像设置模板
本文关键字:于数据 布尔值 图像 设置 数据 | 更新日期: 2023-09-27 18:35:46
这是我的客户类及其集合,我想在页面中显示它。
public class Customer
{
public string Name { get; set; }
public bool Validated { get; set; }
public string Details { get; set; }
}
List<Customer> Customers = new List<Customer>()
{
new Customer() { Validated = false, Name = "Dude", Details = "some details" },
new Customer() { Validated = false, Name = "Person", Details = "some details" },
new Customer() { Validated = true, Name = "Friend", Details = "some details" },
new Customer() { Validated = false, Name = "Buddy", Details = "some details" },
};
我正在尝试在列表控件中为此数据创建数据模板。对于图像,我想根据"已验证"字段显示不同的图像。以下是我到目前为止所做的,但我不知道如何设置图像模板。
<Page x:Class="MyTestPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="250" d:DesignWidth="500"
Title="MyTestPage" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="5*" />
<RowDefinition />
</Grid.RowDefinitions>
<ListBox x:Name="lst1" Grid.Row="0">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<Label FontFamily="Tahoma" FontSize="20" Content="Name" />
<Label FontFamily="Tahoma" FontSize="18" Content="{Binding Name}" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label FontFamily="Tahoma" FontSize="14" Content="Details" />
<Label FontFamily="Tahoma" FontSize="12" Content="{Binding Details}" />
</StackPanel>
</StackPanel>
<Image Source="{Binding Image}" Height="100" Stretch="UniformToFill" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="5" Grid.Row="1" >
<Button Content="Close" Margin="5" Width="60" Click="Close_Click" />
</StackPanel>
</Grid>
</Page>
关于如何在此数据模板中设置图像模板的任何想法?
创建一个实现 IValueConverter
接口的自定义转换器,该接口根据绑定值返回所需的BitmapImage
,您可能只需要为 Convert
方法创建逻辑,以便将ConvertBack
方法保留原样
将您的转换器添加到资源中,如下所示
<Page.Resources>
<myConverters:MyValueConverter x:Key="MyCustomValueConverter"/>
<!-- dont forget to add the xmlns to the page -->
</page.Resources>
并将其添加到图像的绑定中
XAML 映像将如下所示:
<Image Source="{Binding Validated, Converter={StaticResource MyCustomValueConverter}" Height="100" Stretch="UniformToFill"/>