获取 SQL/Linq-query 变量以在一个 ListBox 中为多类型变量项显示 3 位小数

Getting SQL/Linq-query variable to display 3 decimals for multi-type-variable items in one ListBox

美好的一天

不知道是否有人可以提供帮助。 我打算显示包含以下项的行

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; }
}

形式为XamlListBox

<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

如何获取 SQL/Linq-查询变量 'display' 以强制 {Binding ChemWeight} 显示 3 位小数,考虑到其他成员 ChemCat 和 ChemName 是字符串并且它们都在一个列表框。

(前面post说的是ChemPrice,本来是ChemWeight) 非常感谢。

对于 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();
    }
}

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

<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>