使SQL/Linq查询变量在一个ListBox中显示多类型变量项的3位小数

本文关键字:显示 ListBox 类型变量 小数 3位 一个 查询 Linq SQL 变量 | 更新日期: 2023-09-27 18:26:19

不知道是否有人能帮忙。我打算显示包含以下项目的行

public class Product
{
    [PrimaryKey, AutoIncrement]
    public int ChemID { get; set; }
    public string ChemCat { get; set; }
    public string ChemName { get; set; }
    public double ChemWeight { get; set; }
}

以Xaml ListBox 的形式

<ListBox Name="listChems" Height="200" Width="300" HorizontalAlignment="Left" Margin="0,5,0,0" ScrollViewer.VerticalScrollBarVisibility="Visible">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" Height="18" VerticalAlignment="Top" >
                         <TextBlock Text="{Binding ChemCat}" Margin="10,0,0,0" Width="90" FontSize="14"/>
                        <TextBlock Text="{Binding ChemName}" Margin="10,0,0,0" Width="90" FontSize="14"/>
                        <TextBlock Text="{Binding ChemWeight}" Margin="10,0,0,0" Width="60" FontSize="14"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
</ListBox>

使用通常的SQL/Linq查询

private void btnDisplayAll_Click(object sender, RoutedEventArgs e)
    {
        var display = conn.Table<Product>()
        .Select(g => g);
        listChems.ItemsSource = display;
    }

ChemCat和ChemName是纯字符串,例如分别为镧和钕。

然而,我需要ChemWeight(类型double)以3位小数显示,即使用户提供了一个具有0、1或2位小数的数字,即

1 to be displayed as 1.000 
1.4 to be displayed as 1.400
1.42 to be displayed as 1.420

考虑到其他成员ChemCat和ChemName是字符串,并且它们都绑定在一个ListBox中,我如何让SQL/Linq查询变量"display"强制{Binding ChemWeight}显示3位小数。

(早些时候的帖子说ChemPrice,它本应是ChemWeight)非常感谢。

使SQL/Linq查询变量在一个ListBox中显示多类型变量项的3位小数

对于WPF
在绑定中使用StringFormat属性。

<TextBlock Text="{Binding ChemPrice, StringFormat={}{0:0.000}}" Margin="10,0,0,0" Width="60" FontSize="14"/>

对于WINRT使用IValueConverter

public class StringFormatConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return string.Format((string)parameter, value);
    }
    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

请注意,您需要为控件或窗口指定转换器。

<UserControl.Resources>
    <local:StringFormatConverter x:Key="Converter"></local:StringFormatConverter>
</UserControl.Resources>
<Grid>
    <TextBlock Text="{Binding ChemPrice, Converter={StaticResource Converter}, ConverterParameter='{0:0.00'}}" Margin="10,0,0,0" Width="60" FontSize="14"/>
</Grid>