簡體   English   中英

以編程方式更改WPF Datagrid單元的內容

[英]Programatically change the contents of a WPF Datagrid Cell

我有一個WPF DataGrid(.NET Framework 4),它從myObject數組獲取其ItemsSource。 myObject的列/變量之一是DateTime。 有沒有一種方法可以更改DataGrid行的繪制事件,以便我可以在該列的單元格中顯示除每個對象的DateTime以外的其他內容?

設置AutoGenerateColumns為False,並確定使用手動將列DataGridTextColumn ,DataGridTemplateColumn`等。


使用AutoGeneratingColumn事件進行編輯 ,您可以通過添加IValueConverter來修改列的輸出:

    void MyGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        // check if the current column is the target
        if (e.PropertyName == "MyDateproperty")
        {
            // assuming it's a Text-type column
            var column = (e.Column as DataGridTextColumn);
            if (column != null)
            {
                var binding = column.Binding as Binding;
                if (binding != null)
                {
                    // add a converter to the binding
                    binding.Converter = new StringFormatConverter();
                }
            }
        }
    }

現在,以通常的方式定義StringFormatConverter ,將Date / Time值轉換為:

public class StringFormatConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var col = (DateTime?)value;
        return (col == null) ? null : col.Value.ToShortDateString();
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

暫無
暫無

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

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