简体   繁体   English

如何在C#代码后面的ListView中将字符串添加到WPF DataBinding?

[英]How to add string to WPF DataBinding in ListView in C# code behind?

I would like to add a string to my DataBinding with C# code behind and show them in a ListView column.我想用 C# 代码向我的 DataBinding 添加一个字符串,并将它们显示在 ListView 列中。 For example I need to add "USD" string to the current_price binding and show in the ListView.例如,我需要将“USD”字符串添加到 current_price 绑定并显示在 ListView 中。

I have tried to solve the issue with string.Format(), but It did not suceed until now.我试图用 string.Format() 解决这个问题,但直到现在才成功。 I also tried string.Format("{0:C}", "current_price"), but it does not worked too.我也尝试了 string.Format("{0:C}", "current_price"),但它也不起作用。

GridView gridView = new GridView();
listView_coins.View = gridView;
gridView.Columns.Add(new GridViewColumn
{
    Header = "#",
    DisplayMemberBinding = new Binding("market_cap_rank")
});
gridView.Columns.Add(new GridViewColumn
{
    Header = "Name",
    DisplayMemberBinding = new Binding("name")
});
gridView.Columns.Add(new GridViewColumn
{
    Header = "Ticker",
    DisplayMemberBinding = new Binding("symbol")
});
gridView.Columns.Add(new GridViewColumn
{
    Header = "Change (24h)",
    DisplayMemberBinding = new Binding("price_change_percentage_24h")
});
gridView.Columns.Add(new GridViewColumn
{
    Header = "Price",
    DisplayMemberBinding = new Binding(string.Format("{0} USD", "current_price"))
});

for (int i = 0; i < coinDatas.Count; i++)
{
    listView_coins.Items.Add(new CryptocurrencyDataModel
    {
        market_cap_rank = coinDatas[i].market_cap_rank,
        name = coinDatas[i].name,
        symbol = coinDatas[i].symbol.ToUpper(),
        price_change_percentage_24h = coinDatas[i].price_change_percentage_24h,
        current_price = coinDatas[i].current_price,
    });
}

I would like to get a result like 17.260 USD in the ListView column.我想在 ListView 列中得到类似 17.260 USD 的结果。

It is necessary not to set the path to the format string, but to set the value of the format string to the binding有必要不设置格式字符串的路径,而是将格式字符串的值设置为绑定

gridView.Columns.Add(new GridViewColumn
{
    Header = "Price",
    DisplayMemberBinding = new Binding(nameof(CryptocurrencyDataModel.current_price))
    {
        StringFormat="{0} USD"
    }
});

PS You can also set the m.netary format of the output once in XAML, and adjust the display of the desired currency by changing the culture language of the UI element. PS也可以在XAML中设置一次output的m.netary格式,通过改变UI元素的文化语言来调整所需货币的显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM