簡體   English   中英

WPF GridView gridviewcolumn 綁定上每個項目的不同字符串格式

[英]WPF GridView different stringformat for each item on gridviewcolumn binding

我正在嘗試根據每個數據上下文項目分別綁定列綁定的 StringFormat。

這是示例代碼:

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>

背后的代碼:

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


    }

StringFormat={Binding StringFormat}是不可能的,我只是把它放在那里來演示我到底想要什么。 每個項目的(符號)格式都不同。

如果我需要在后面的代碼中添加列並不重要,我可以做到,但我只是不知道該怎么做。

有什么建議么? 謝謝你。

更新:有一個我不想使用的解決方案,但現在我相信這是唯一合乎邏輯的方法。

private double _price;
public double Price
{
    get => _price;
    set
    {
        _price = value;
        OnPropertyChanged(nameof(Price));
        StringPrice = value.ToString(format);
    }
}
private string _stringprice;
public string StringPrice
{
    get => _stringprice;
    set {
        _stringprice = value;
        OnPropertyChanged(nameof(StringPrice));
    }
}

並在 XAML 中使用它:

<GridViewColumn Header="Price" DisplayMemberBinding="{Binding StringPrice}" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM