I'm trying to bind the StringFormat of a column binding depending on each datacontext item's individually.
Here's the sample code:
xaml:
<ListView ItemsSource="{Binding Symbols}">
<ListView.View>
<GridView x:Name="gw">
<GridView.Columns>
<GridViewColumn Header="Symbol" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Header="Price" DisplayMemberBinding="{Binding Price, StringFormat={Binding StringFormat}}" />
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
code behind:
public ObservableCollection<symbol> Symbols { get;set;}
public class symbol : INotifyPropertyChanged
{
#region INotify Handler
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
#endregion
private string _name;
public string Name
{
get => _name;
set
{
_name = value;
OnPropertyChanged(nameof(Name));
}
}
private double _price;
public double Price
{
get => _price;
set
{
_price = value;
OnPropertyChanged(nameof(Price));
}
}
private int _decimalplaces;
public int decimalplaces
{
get => _decimalplaces;
set
{
_decimalplaces = value;
OnPropertyChanged(nameof(decimalplaces));
if (value == 0)
StringFormat = "0";//no decimal
else
StringFormat = $"0.{new string('0', value)}";//like 0.000 for 3 decimal places
}
}
public string StringFormat { get; set; }
}
The StringFormat={Binding StringFormat} is not possible, I've just put it there to demonstrate what I exactly wanted. Each item's (symbol) format is different.
It doesn't matter if I need to add the columns in code behind, I can do it but I just don't know how to.
Any suggestions? Thank you.