This is a migrated thread and some comments may be shown as answers.

Unable to properly bind to custom business object.

1 Answer 32 Views
GridView
This is a migrated thread and some comments may be shown as answers.
Steele
Top achievements
Rank 1
Steele asked on 09 Oct 2012, 09:24 PM
Using this to represent rows of data...

using
System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.ComponentModel;
 
using LyndWorld.LiveWire.SilverlightUI.Web.Models;
 
namespace LyndWorld.LiveWire.SilverlightUI.Entities
{
    public class LiveWireDataRow : DynamicObject, INotifyPropertyChanged
    {
        readonly IDictionary<string, object> _data;
 
        public LiveWireDataRow()
        {
            _data = new Dictionary<string, object>();
        }
 
 
        public LiveWireDataRow(IDictionary<string, object> source)
        {
            _data = source;
        }
 
        public override IEnumerable<string> GetDynamicMemberNames()
        {
            return _data.Keys;
        }
 
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = this[binder.Name];
 
            return true;
        }
 
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            this[binder.Name] = value;
 
            return true;
        }
 
        public object this[string columnName]
        {
            get
            {
                if (_data.ContainsKey(columnName))
                {
                    return _data[columnName];
                }
 
                return null;
            }
 
            set
            {
                if (!_data.ContainsKey(columnName))
                {
                    _data.Add(columnName, value);
 
                    OnPropertyChanged(columnName);
                }
                else
                {
                    if (_data[columnName] != value)
                    {
                        _data[columnName] = value;
 
                        OnPropertyChanged(columnName);
                    }
                }
            }
        }
 
        public void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
 
        public event PropertyChangedEventHandler PropertyChanged;
    }
}

and using this to represent cells of data...

namespace LyndWorld.LiveWire.SilverlightUI.Entities
{
    public class LiveWireDataCell
    {
        private object _value;
        private string _referenceUrl;
 
        public LiveWireDataCell(object pValue)
        {
            _value = pValue;
        }
 
        public LiveWireDataCell(object pValue, string pReferenceUrl)
        {
            _value = pValue;
            _referenceUrl = pReferenceUrl;
        }
 
        public object Value { get; set; }
 
        public string ReferenceUrl { get; set; }
    }
}

The grid doesnt know to call the Value property of the LiveWireDataCell object to get its display value. See the code below for how I am building and binding.

using System.Globalization;
using System.Threading.Tasks;
 
namespace LyndWorld.LiveWire.SilverlightUI
{
    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.ServiceModel.DomainServices.Client;
    using System.Windows.Data;
    using Web.Services;
    using Web.Models;
    using Entities;
    using System.Collections.ObjectModel;
    using System.Collections.Generic;
    using System.Linq;
    using Helpers;
    using Telerik.Windows.Controls.GridView;
    using Telerik.Windows.Controls;
    using Telerik.Windows.Data;
    /// <summary>
    /// <see cref="UserControl"/> class providing the main UI for the application.
    /// </summary>
    public partial class MainPage
    {
        private const string UserName = "skennett";
        private LiveWireContext _context;
        private LoadOperation<LiveWireDataColumn> _dataColumnOperation;
        private LiveWireUser _user;
        private LoadOperation<GetLiveWireViewsByUserId_Result> _userViewsOperation;
        private LoadOperation<GetLiveWireDataSetsByUserId_Result> _userDataSetsOperation;
        private LoadOperation<GetDataPoints_Result> _dataPointsOperation;
 
        /// <summary>
        /// Creates a new <see cref="MainPage"/> instance.
        /// </summary>
        public MainPage()
        {
            InitializeComponent();
 
            Loaded         += MainPageLoaded;
            SizeChanged    += MainPageSizeChanged;
        }
 
        void MainPageSizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (!Application.Current.Host.Content.IsFullScreen)
            {
                gvLiveWire.MaxHeight   = 280;
                gvLiveWire.ScrollMode  = ScrollUpdateMode.RealTime;
            }
            else
            {
                gvLiveWire.MaxHeight   = (e.NewSize.Height - 100);
                gvLiveWire.ScrollMode  = ScrollUpdateMode.Deferred;
            }
        }
 
        private async void InitializeLiveWire()
        {
            LiveWireBusyIndicator.IsBusy = true;
 
            await HandleAsyncCalls();
             
            InitializeUserViews();
             
            InitializeUserDataSets();
 
            InitializeDataColumns();
 
            await InitializeDataPoints();
 
            LiveWireBusyIndicator.IsBusy = false;
        }
 
        private async Task<int> HandleAsyncCalls()
        {
            var userIdOperation = await _context.Load(
                _context.GetUserIdByUsernameQuery(UserName)
                ).AsTask();
 
            if (!userIdOperation.Entities.Any())
            {
                throw new Exception("User ID not found.");
            }
 
            var userId = userIdOperation.Entities.First().Id;
            var userOperation = await _context.Load(
                    _context.GetLiveWireUserByIdQuery(userId)
                ).AsTask();
 
            _user = userOperation.Entities.First();
            _userViewsOperation = await _context.Load(
                _context.GetLiveWireViewsByUserIdQuery(_user.Id)
            ).AsTask();
 
            _userDataSetsOperation = await _context.Load(
                _context.GetLiveWireDataSetsByUserIdQuery(_user.Id,
                _user.UserRoleMappings.First().LiveWireRoleId)
            ).AsTask();
 
            _dataColumnOperation = await _context.Load(
                _context.GetDataColumnsQuery(_user.DefaultDataSet)
            ).AsTask();
 
            _dataPointsOperation = await _context.Load(
                _context.GetDataPointsQuery(_user.Id,
                    _user.UserRoleMappings.First().LiveWireRoleId,
                    _user.DefaultDataSet, _user.DefaultView, true)
            ).AsTask();
 
            return 0;
        }
 
        private void InitializeUserViews()
        {
            var root = new ObservableCollection<ViewMenuItem>();
            var subItems = new ObservableCollection<ViewMenuItem>();
            var views = new ViewMenuItem(0) { Text = "Views" };
 
            foreach (var item in
                from result in _userViewsOperation.Entities
                where result.ParentId == null
                let id = result.Id
                where id != null
                select new ViewMenuItem(id.Value) { Text = result.Name })
            {
                item.SubItems = GetChildren(item, _userViewsOperation.Entities);
 
                subItems.Add(item);
            }
 
            views.SubItems = subItems;
 
            root.Add(views);
 
            mnuViews.ItemsSource = root;
            mnuViews.ItemClick += MnuViewsItemClick;
        }
 
        private void InitializeUserDataSets()
        {
            var dataSets = new ObservableCollection<DataSetMenuItem>();
            var dataSetsSubItems = new ObservableCollection<DataSetMenuItem>();
 
            var dataSetsItem = new DataSetMenuItem(Guid.NewGuid()) { Text = "Data Sets" };
 
            foreach (
                var item in _userDataSetsOperation.Entities.Select(
                result => new DataSetMenuItem(result.Id) { Text = result.Name })
                )
            {
                dataSetsSubItems.Add(item);
            }
 
            dataSetsItem.SubItems = dataSetsSubItems;
            dataSets.Add(dataSetsItem);
 
            mnuDataSet.ItemsSource = dataSets;
        }
 
        private void InitializeDataColumns()
        {
            var idCol = new GridViewDataColumn
            {
                Header = "Id",
                DisplayIndex = 0,
                DataMemberBinding = new Binding("Id"),
                DataType = typeof(String),
                UniqueName = "Id"
            };
 
            gvLiveWire.Columns.Add(idCol);
 
            foreach (var column in _dataColumnOperation.Entities)
            {
                var gvdc = new GridViewDataColumn
                {
                    Header = column.Name,
                    DisplayIndex = column.Ordinal,
                    UniqueName = column.Name.Replace(" ", String.Empty)
                };
 
                gvdc.DataMemberBinding = new Binding(gvdc.UniqueName);
                gvdc.TextAlignment = TextAlignment.Right;
                gvdc.FooterTextAlignment = TextAlignment.Right;
 
                switch (column.DisplayDataTypeId)
                {
                    case (int)DisplayDataType.Currency:
 
                        gvdc.DataType = typeof(Decimal);
                        gvdc.DataFormatString = "{0:C}";
 
                        switch (column.LiveWireDataColumnFooterFormula.Id)
                        {
                            case (int)Entities.LiveWireDataColumnFooterFormula.Sum:
 
                                gvdc.AggregateFunctions.Add(new AggregateFunction<LiveWireDataRow, Decimal>
                                {
                                    AggregationExpression =
                                        total => total.Sum(row => Convert.ToDecimal(row[gvdc.UniqueName])),
                                    ResultFormatString = gvdc.DataFormatString
                                }
                                    );
                                break;
 
                            case (int)Entities.LiveWireDataColumnFooterFormula.Average:
 
                                gvdc.AggregateFunctions.Add(
                                    new AggregateFunction<LiveWireDataRow, Decimal>
                                    {
                                        AggregationExpression =
                                            total => total.Average(row => Convert.ToDecimal(row[gvdc.UniqueName])),
                                        ResultFormatString = gvdc.DataFormatString
                                    }
                                    );
                                break;
                        }
                        break;
 
                    case (int)DisplayDataType.Date:
 
                        gvdc.DataType = typeof(DateTime);
                        gvdc.DataFormatString = "{0:d}";
                        gvdc.TextAlignment = TextAlignment.Left;
                        break;
 
                    case (int)DisplayDataType.Number:
 
                        gvdc.DataType = typeof(Int32);
                        gvdc.DataFormatString = "{0:N0}";
 
                        switch (column.LiveWireDataColumnFooterFormula.Id)
                        {
                            case (int)Entities.LiveWireDataColumnFooterFormula.Sum:
 
                                gvdc.AggregateFunctions.Add(
                                    new AggregateFunction<LiveWireDataRow, Int32>
                                    {
                                        AggregationExpression =
                                            total => total.Sum(row => Convert.ToInt32(row[gvdc.UniqueName])),
                                        ResultFormatString = gvdc.DataFormatString
                                    }
                                    );
                                break;
 
                            case (int)Entities.LiveWireDataColumnFooterFormula.Average:
 
                                gvdc.AggregateFunctions.Add(
                                    new AggregateFunction<LiveWireDataRow, Double>
                                    {
                                        AggregationExpression =
                                            total => total.Average(row => Convert.ToInt32(row[gvdc.UniqueName])),
                                        ResultFormatString = gvdc.DataFormatString
                                    }
                                    );
                                break;
                        }
                        break;
 
                    case (int)DisplayDataType.Percentage:
 
                        gvdc.DataType = typeof(Decimal);
                        gvdc.DataFormatString = "{0:P}";
 
                        switch (column.LiveWireDataColumnFooterFormula.Id)
                        {
                            case (int)Entities.LiveWireDataColumnFooterFormula.Sum:
 
                                gvdc.AggregateFunctions.Add(
                                    new AggregateFunction<LiveWireDataRow, Decimal>
                                    {
                                        AggregationExpression =
                                            total => total.Sum(row => Convert.ToDecimal(row[gvdc.UniqueName])),
                                        ResultFormatString = gvdc.DataFormatString
                                    }
                                    );
                                break;
 
                            case (int)Entities.LiveWireDataColumnFooterFormula.Average:
 
                                gvdc.AggregateFunctions.Add(
                                    new AggregateFunction<LiveWireDataRow, Decimal>
                                    {
                                        AggregationExpression =
                                            total => total.Average(row => Convert.ToDecimal(row[gvdc.UniqueName])),
                                        ResultFormatString = gvdc.DataFormatString,
                                    }
                                    );
                                break;
                        }
                        break;
 
                    default:
 
                        gvdc.DataType = typeof(String);
                        gvdc.TextAlignment = TextAlignment.Left;
                        break;
                }
 
                gvLiveWire.Columns.Add(gvdc);
            }
        }
 
        private async Task<int> InitializeDataPoints()
        {
            var data = new List<LiveWireDataRow>();
            var distinctPropertyIds = _dataPointsOperation.Entities.Select(
                e => e.PropertyId).Distinct();
 
            foreach (var propertyId in distinctPropertyIds)
            {
                var row = new LiveWireDataRow();
 
                row["Id"] = propertyId;
 
                foreach (var column in _dataColumnOperation.Entities)
                {
                    string value = null;
                    string referenceUrl = null;
                    var uniqueName = column.Name.Replace(" ", string.Empty);
 
                    if (!string.IsNullOrEmpty(column.CustomProcedureName))
                    {
                        var columnValue = await _context.ExecuteCustomProcedure(
                            column.CustomProcedureName, propertyId).AsTask();
 
                        value = columnValue.Value;
                    }
                    else
                    {
                        var column1 = column;
                        var id      = propertyId;
                        var col     = from e in _dataPointsOperation.Entities
                                      where e.LiveWireDataColumnId == column1.Id
                                            && e.PropertyId == id
                                      select e;
 
                        var getDataPointsResults
                            = col as GetDataPoints_Result[] ?? col.ToArray();
                         
                        if (getDataPointsResults.Any())
                        {
                            value = getDataPointsResults.First().Value;
                             
                            if (!string.IsNullOrEmpty(
                                getDataPointsResults.First().ReferenceUrl))
                            {
                                referenceUrl = getDataPointsResults.First().ReferenceUrl;
                            }
                        }
                    }
 
                    var cell = new LiveWireDataCell(value);
 
                    if (!string.IsNullOrEmpty(referenceUrl))
                    {
                        cell.ReferenceUrl = referenceUrl;
                    }
 
                    switch (column.DisplayDataTypeId)
                    {
                        case (int) DisplayDataType.Currency:
 
                            cell.Value = Convert.ToDecimal(cell.Value);
                            row[uniqueName] = cell;
                            break;
                        case (int) DisplayDataType.Date:
 
                            cell.Value = Convert.ToDateTime(cell.Value);
                            row[uniqueName] = cell;
                            break;
                        case (int) DisplayDataType.Number:
 
                            cell.Value = Convert.ToInt32(cell.Value);
                            row[uniqueName] = cell;
                            break;
                        case (int) DisplayDataType.Percentage:
 
                            cell.Value = Convert.ToDecimal(cell.Value);
                            row[uniqueName] = cell;
                            break;
                        case (int) DisplayDataType.Text:
 
                            row[uniqueName] = cell;
                            break;
                    }
                }
 
                data.Add(row);
            }
             
            gvLiveWire.RowLoaded   += GvLiveWireRowLoaded;
            gvLiveWire.ItemsSource = data;
 
            return 0;
        }
 
        void GvLiveWireRowLoaded(object sender, RowLoadedEventArgs e)
        {
            return;
            var row = e.Row as GridViewRow;
 
            foreach (var column in _dataColumnOperation.Entities)
            {
                foreach (var code in column.ColorCodes.OrderBy(o => o.Ordinal))
                {
                    List<GridViewCell> cells;
 
                    try
                    {
                        cells = row.ChildrenOfType<GridViewCell>()
                            .Where(n => n.Column.UniqueName
                                == column.Name.ToString(CultureInfo.InvariantCulture)
                                .Replace(" ", String.Empty))
                            .ToList();
                    }
                    catch (Exception)
                    {
                        return;
                    }
 
                    foreach (var cell in cells)
                    {
                        switch (column.DisplayDataTypeId)
                        {
                            case (int)DisplayDataType.Percentage:
                                var cellValue = Convert.ToDecimal(cell.Value.ToString()
                                    .Replace("%", String.Empty));
 
                                cellValue = cellValue / 100;
 
                                var codeValue = Convert.ToDecimal(code.Value);
 
                                switch (code.ColorCodeOperatorId)
                                {
                                    case (int)ColorCodeOperator.IsGreaterThanOrEqualTo:
                                        if (cellValue >= codeValue)
                                        {
                                            cell.Background = ColorUtility.GetBrushFromHex(code.Color);
                                        }
                                        break;
                                    case (int)ColorCodeOperator.IsLessThanOrEqualTo:
                                        if (cellValue <= codeValue)
                                        {
                                            cell.Background = ColorUtility.GetBrushFromHex(code.Color);
                                        }
                                        break;
                                }
                                break;
                        }
                    }
                }
            }
        }
 
        void MainPageLoaded(object sender, RoutedEventArgs e)
        {
            _context = new LiveWireContext();
 
            InitializeLiveWire();
 
            btnLyndWorldMap.Click += BtnLyndWorldMapClick;
        }
 
        static void BtnLyndWorldMapClick(object sender, RoutedEventArgs e)
        {
            var window = new Views.LyndWorldMap();
 
            window.Show();
        }
 
        private static ObservableCollection<ViewMenuItem> GetChildren(ViewMenuItem pParent, IEnumerable<GetLiveWireViewsByUserId_Result> results)
        {
            var menuItems = new ObservableCollection<ViewMenuItem>();
 
            var getLiveWireViewsByUserIdResults = results as GetLiveWireViewsByUserId_Result[] ?? results.ToArray();
            var query = getLiveWireViewsByUserIdResults.Where(e => e.ParentId == pParent.Id);
 
            foreach (var item in
                from result in query
                let id = result.Id
                where id != null
                select new ViewMenuItem(id.Value) {Text = result.Name})
            {
                item.SubItems = GetChildren(item, getLiveWireViewsByUserIdResults);
 
                menuItems.Add(item);
            }
 
            return menuItems;
        }
 
        static void MnuViewsItemClick(object sender, Telerik.Windows.RadRoutedEventArgs e)
        {
 
        }
 
        private void QaFullScreenClick(object sender, RoutedEventArgs e)
        {
            Application.Current.Host.Content.IsFullScreen
                = !Application.Current.Host.Content.IsFullScreen;
        }
    }
}

How can I fix this? 

1 Answer, 1 is accepted

Sort by
0
Vlad
Telerik team
answered on 12 Oct 2012, 05:50 AM
Hi,

 I'm not sure I understand the problem. Do you have this working with standard Silverlight DataGrid and not working with RadGridView?

All the best,
Vlad
the Telerik team

Explore the entire Telerik portfolio by downloading Telerik DevCraft Ultimate.

Tags
GridView
Asked by
Steele
Top achievements
Rank 1
Answers by
Vlad
Telerik team
Share this question
or