简体   繁体   中英

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. For example I need to add "USD" string to the current_price binding and show in the ListView.

I have tried to solve the issue with string.Format(), but It did not suceed until now. I also tried string.Format("{0:C}", "current_price"), but it does not worked too.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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