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

The simple example of implementation ViewModel with support of CRUD RadGridView commands POCO entities, MVVM, RIA Service, EF4 code first CTP5

2 Answers 397 Views
GridView
This is a migrated thread and some comments may be shown as answers.
Alexander Lev
Top achievements
Rank 1
Alexander Lev asked on 22 Mar 2011, 02:43 PM
In the project I use Silverlight4, Telerik Q1 2011: RadGridView, MVVM, WCF RIA Service, ORM EF 4 code first CTP 5

1. Domain Model Layer: POCO class:
// My Register ModBus Protocol
public
partial class RegAssign
{
    [Key]
    public long Id { get; set; }
    public string Code { get; set; }
    public string Description { get; set; }
    public int ModBusReg { get; set; }
    public int MinRegNum { get; set; }
    public int MaxRegNum { get; set; }
}
2. Data Access Layer: DbContext
public class EFContext : DbContext
{
        public EFContext() : base("ApplicationServices"
        {
            Configuration.LazyLoadingEnabled = false;
        }
        public DbSet<RegAssign>     RegAssigns      { get; set; }
}
3. Domain Service Layer: WCF RIA Service WCF RIA Services with EF4 CTP5
RegAssignService.cs
[EnableClientAccess()]
public class RegAssignDomainService : DomainService
{
    public RegAssignDomainService()
    {
        this.Container = new EFContext();
    }
    private EFContext Container { get; set; }
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            this.Container.Dispose();
        }
        base.Dispose(disposing);
    }
    protected override bool PersistChangeSet()
    {
        this.Container.SaveChanges();
        return base.PersistChangeSet();
    }
    public ObjectContext ObjectContext
    {
        get
        {
            return ((IObjectContextAdapter)this).ObjectContext;
        }
    }
    public IEnumerable<RegAssign> GetRegAssigns()
    {
        return this.Container.RegAssigns.OrderBy(a => a.ModBusReg).ToList();
    }
    public void InsertRegAssign(RegAssign obj)
    {
        this.Container.Insert(obj);
    }
    public void UpdateRegAssign(RegAssign currentRegAssign)
    {
        this.Container.Update(currentRegAssign, this.ChangeSet.GetOriginal(currentRegAssign));
    }
    public void DeleteRegAssign(RegAssign obj)
    {
        this.Container.Delete(obj);
    }
    private static Expression<Func<RegAssign, string>> CreateSelectorExpression(string propertyName)
    {
        var paramterExpression = Expression.Parameter(typeof(RegAssign));
        return (Expression<Func<RegAssign, string>>)Expression.Lambda(Expression.PropertyOrField(paramterExpression,   propertyName), paramterExpression);
    }
}
RegAssignService.metadata.cs
[MetadataType(typeof(RegAssignMetadata))]
public class RegAssign
{
    #region Nested type: RegAssignMetadata
    internal sealed class RegAssignMetadata
    {
        // Metadata classes are not meant to be instantiated.
        private RegAssignMetadata()
        {
        }
        public long Id { get; set; }
        public string Code { get; set; }
        public string Description { get; set; }
        public int ModBusReg { get; set; }
        public int MinRegNum { get; set; }
        public int MaxRegNum { get; set; }
    }
    #endregion
}
4. Silverlight Navigate Application - View Layer:
RegAssignView.xaml on blog's Support MVVM and Domain Data Source MVVM support
<Grid x:Name="LayoutRoot">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition />
        </Grid.RowDefinitions>
  
        <Border telerikQuickStart:ThemeAwareBackgroundBehavior.IsEnabled="True" Grid.RowSpan="2" />
  
        <StackPanel Name="ConfigurationPanel" 
                    Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,5,0,0">
            <telerik:RadButton Width="150" Content="Delete selected" Margin="0,0,5,0" 
                               Command="{Binding DeleteCommand}"
                               CommandParameter="{Binding ElementName=mainGrid, Path=SelectedItem}"
                               Visibility="{Binding IsDeleteCommandAvailable, Converter={StaticResource BooleanToVisibilityConverter}}"  />
            <telerik:RadButton Width="150" Content="Add New" Margin="0,0,5,0" 
                               Command="{Binding DeleteCommand}"
                               CommandParameter="{Binding ElementName=mainGrid, Path=SelectedItem}"
                               Visibility="{Binding IsInsertCommandAvailable, Converter={StaticResource BooleanToVisibilityConverter}}"
                               />
            <telerik:RadButton Width="150" Content="Save edit" Margin="0,0,5,0"
                               Command="telerikGrid:RadGridViewCommands.CommitEdit"   
                               CommandTarget="{Binding ElementName=mainGrid}"  />
            <telerik:RadButton Width="150" Content="Cancel edit"
                               Command="telerikGrid:RadGridViewCommands.CancelRowEdit"   
                               CommandTarget="{Binding ElementName=mainGrid}"  />
        </StackPanel>
                        <!-- SelectionMode="Extended" -->
        <telerik:RadGridView x:Name="mainGrid" 
                             ItemsSource="{Binding View}" 
                             SelectedItem="{Binding SelectedItem}"
                             AutoGenerateColumns="False" 
                             Margin="0,5,0,0" 
                             Grid.Row="1" 
                             ActionOnLostFocus="None" 
                             CanUserDeleteRows="True"
                             IsReadOnly="False"
                             >
            <telerik:RadGridView.Columns>
                <telerik:GridViewDataColumn DataMemberBinding="{Binding Code}" Header="Code"/>
                <telerik:GridViewDataColumn DataMemberBinding="{Binding ModBusReg}" Header="Mod Bus Register"/>
                <telerik:GridViewDataColumn DataMemberBinding="{Binding MinRegNum}" Header="Min Register"/>
                <telerik:GridViewDataColumn DataMemberBinding="{Binding MaxRegNum}" Header="Max Register"/>
                <telerik:GridViewDataColumn DataMemberBinding="{Binding Description}" Header="Description" Width="*"/>
                <telerik:GridViewColumn>
                    <telerik:GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <telerik:RadButton Content="Delete" 
                                               Command="telerikGrid:RadGridViewCommands.Delete" 
                                               CommandParameter="{Binding ElementName=mainGrid, Path=SelectedItem}" />
                        </DataTemplate>
                    </telerik:GridViewColumn.CellTemplate>
                </telerik:GridViewColumn>
            </telerik:RadGridView.Columns>
        </telerik:RadGridView>
    </Grid>

RegAssign.xaml.cs
public partial class RegAssign : Page
{
        public RegAssign()
        {
            InitializeComponent();
            this.mainGrid.Items.DescriptorsSynchronizationMode = SynchronizationMode.TwoWay;
            RegAssignViewModel viewModel = new RegAssignViewModel();
            this.mainGrid.DataContext = viewModel;
            this.ConfigurationPanel.DataContext = viewModel;
        }
}


5 View Model Layer
RegAssignViewModel
    public class RegAssignViewModel : ViewModelBase 
    {
        private QueryableDomainServiceCollectionView<RegAssign> view;
        private IEnumerable<RegAssign> selectedItems; 
        private DelegateCommand loadCommand;
        private ICommand insertCommand;
        private ICommand deleteCommand;
        private ICommand saveCommand;
        private ICommand cancelCommand;
  
        private RegAssignDomainContext context;
  
        public RegAssignViewModel()
        {
            context = new RegAssignDomainContext();
            EntityQuery<RegAssign> getQuery = context.GetRegAssignsQuery();
            this.view = new QueryableDomainServiceCollectionView<RegAssign>(context, getQuery);
  
            this.view.PageSize = 10;
            this.view.AutoLoad = true;
              
            this.view.PropertyChanged += this.OnViewPropertyChanged;
  
            this.loadCommand   = new DelegateCommand(this.ExecuteLoadCommand, this.LoadCommandCanExecute);
            this.insertCommand = new DelegateCommand((o) =>
            {
                view.AddNew(o ?? new RegAssign());
            });
                //RadGridViewCommands.BeginInsert;
            this.saveCommand    = RadGridViewCommands.CommitEdit;
            this.cancelCommand  = RadGridViewCommands.CancelRowEdit;
            this.deleteCommand  = RadGridViewCommands.Delete;
            /*
            this.insertCommand  = new DelegateCommand(this.ExecuteInsertCommand, this.InsertCommandCanExecute);
            //this.editCommand    = new DelegateCommand(this.ExecuteEditCommand, this.EditCommandCanExecute);
            this.deleteCommand  = new DelegateCommand(this.ExecuteDeleteCommand, this.DeleteCommandCanExecute);
            this.saveCommand    = new DelegateCommand(this.ExecuteSaveCommand, this.SaveCommandCanExecute);
            this.cancelCommand  = new DelegateCommand(this.ExecuteCancelCommand, this.CancelCommandCanExecute);
             */ 
        }
  
        public IEnumerable View 
        
            get { return this.view; } 
        }
  
        public RegAssign SelectedItem
        {
            get { return (RegAssign)this.view.CurrentItem; }
        }
  
        public int PageSize
        {
            get { return this.view.PageSize; }
            set
            {
                if (this.view.PageSize != value)
                {
                    this.view.PageSize = value;
                    this.OnPropertyChanged(m => m.PageSize);
                }
            }
        }
  
        public bool AutoLoad
        {
            get { return this.view.AutoLoad; }
            set 
            
                if (this.view.AutoLoad != value)
                {
                    this.view.AutoLoad = value;
                    this.OnPropertyChanged(m => m.AutoLoad);
                }
            }
        }
  
        public ICommand InsertCommand 
        
            get { return insertCommand; } 
        }
/* My unsuccessful implementation of an inserting command RadGridView
        public bool IsInsertCommandAvailable { get { return InsertCommandCanExecute(null); } }
        public ICommand InsertCommand { get { return insertCommand; } }
        private void ExecuteInsertCommand(object o)
        {
            view.AddNew((RegAssign)o ?? new RegAssign());
        }
        private bool InsertCommandCanExecute(object o)
        {
            return view.CanAddNew;
        }
*/
        public bool IsBusy { get { return view.IsBusy; } }
  
        public bool CanLoad { get { return view.CanLoad; } }
        public ICommand LoadCommand { get { return loadCommand; } }
        private void ExecuteLoadCommand(object o) 
        
            view.Load(); 
        }
        private bool LoadCommandCanExecute(object o)
        {
            return CanLoad && ! AutoLoad;
        }
  
        private void OnViewPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "CanLoad":
                    this.loadCommand.InvalidateCanExecute();
                    break;
                case "IsBusy":
                case "AutoLoad":
                    this.OnPropertyChanged(e.PropertyName);
                    this.loadCommand.InvalidateCanExecute();
                    break;
                default:
                    this.OnPropertyChanged(e.PropertyName);
                    break;
            }
        }

In my View RadButtons in RadGridView does not work at any variants of a binding and implemenation of commands to ViewModel!

My request:
Very simple example of implementation in ViewModel CRUD —Āommands RadGridView 
using magic QueryableDomainServiceCollectionView

Thanks

2 Answers, 1 is accepted

Sort by
0
Maya
Telerik team
answered on 22 Mar 2011, 02:52 PM
Hi Alexander Lev,

May you try to initialize the commands as demonstrated in our demo:

public Example()
    {
        ICommand deleteCommand = RadGridViewCommands.Delete;
        ICommand beginInsertCommand = RadGridViewCommands.BeginInsert;
        ICommand cancelRowEditCommand = RadGridViewCommands.CancelRowEdit;
        ICommand commitEditCommand = RadGridViewCommands.CommitEdit;
 
        InitializeComponent();
    }

 

All the best,
Maya
the Telerik team
0
Alexander Lev
Top achievements
Rank 1
answered on 22 Mar 2011, 03:41 PM

Quite right, but this example does not use MVVM template!

I ask to show example ViewModel with implementation of CRUD commands with
context through QueryableDomainServiceCollectionView (view property in my VM).
Probably there is an example of implementation GridViewModel for RIA Service

Thank Maya for yours so a prompt reply
Tags
GridView
Asked by
Alexander Lev
Top achievements
Rank 1
Answers by
Maya
Telerik team
Alexander Lev
Top achievements
Rank 1
Share this question
or