简体   繁体   中英

dynamically add months as datagrid columns using xaml

I'm trying to add the previous 12 months as columns in a Datagrid but I'm kinda stuck. I'd like them to be displayed like :

May 2014 June 2014 July 2014 August 2014 .... May 2015 in XAML if it's possible. In July ie would be July 2014 August 2014 .... July 2014

At the moment I achieved it by using code behind but I'd like to do it using XAML.

var nameCol = new DataGridTextColumn();
nameCol.Heade = "Name";

for (int i = -12; i <= 0; i++)
        {
            var lastYearMonth = DateTime.Now.AddMonths(i).ToString("Y");
            var col = new DataGridTextColumn();
            col.Header =  lastYearMonth;
            col.Binding = new Binding("CategoryIncome");
            monthlyCategories.Columns.Add(col);
        }
var total = new DataGridTextColumn();
total.Header = "Total";

Generally if you want to express some behavior/logic in XAML without writing any code behind, the aptly named "behaviors" are a good solution. See this introduction for example.

Another possibility would be to create the months strings in the view model and use data binding for the header. You may have to create a special header template for doing that.

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