Binding a Grouped Table View using Xamarin.iOS and MvvmCross - c#

I am trying to create a Grouped Table View using Xamarin.iOS and MvvmCross. But can't get the binding part right, my ItemSource is always null and RaisePropertyChanged in the ViewModel won't trigger the the setter of my ItemsSource. I have looked at the conference sample Stuart refers to in Creating UITable with section using Mono touch and slodge mvvmcross, but I am currently stuck where I am.
This is the TableSource I am using:
public class VoiceMessagesTableSource : MvxTableViewSource
{
private List<VoiceMessagesTableItemGroup> _itemsSource;
private const string _cellNibName = "MessagesTableCell";
private static readonly NSString _cellIdentifier = new NSString(_cellNibName);
public VoiceMessagesTableSource(UITableView tableView) : base(tableView)
{
tableView.RegisterNibForCellReuse(UINib.FromName(_cellNibName, NSBundle.MainBundle), _cellIdentifier);
}
public List<VoiceMessagesTableItemGroup> ItemsSource
{
get
{
return _itemsSource;
}
set
{
_itemsSource = value;
ReloadTableData();
}
}
public override int NumberOfSections(UITableView tableView)
{
if (_itemsSource == null)
{
return 0;
}
return _itemsSource.Count;
}
public override int RowsInSection(UITableView tableview, int section)
{
if (_itemsSource == null)
{
return 0;
}
return _itemsSource[section].Count;
}
protected override UITableViewCell GetOrCreateCellFor(UITableView tableView, NSIndexPath indexPath, object item)
{
return (UITableViewCell)TableView.DequeueReusableCell(_cellIdentifier, indexPath);
}
protected override object GetItemAt(NSIndexPath indexPath)
{
if (_itemsSource == null)
{
return null;
}
return _itemsSource[indexPath.Section][indexPath.Row];
}
}
This is how I bind it in the view:
private void BindMessagesTable()
{
var data_source = new VoiceMessagesTableSource(MessagesTable);
MvxFluentBindingDescriptionSet<MessagesView, MessagesViewModel> set = this.CreateBindingSet<MessagesView, MessagesViewModel>();
//set.Bind(data_source).To(viewModel => viewModel.GroupedVoiceMessages);
set.Bind(data_source.ItemsSource).To(viewModel => viewModel.GroupedVoiceMessages);
set.Bind(data_source).For(s => s.SelectionChangedCommand).To(viewModel => viewModel.DisplayVoiceMessageCommand);
set.Apply();
MessagesTable.Source = data_source;
MessagesTable.ReloadData();
}
And this is the ItemGroup class I am using as my items source:
public class VoiceMessagesTableItemGroup : List<MessageEntryViewModel>
{
public VoiceMessagesTableItemGroup(string key, IEnumerable<MessageEntryViewModel> items) : base(items)
{
Key = key;
}
public string Key { get; set; }
}

I've not analysed all the code in the question, but one issue I can see is that it looks like you are trying to Bind the wrong target.
When you write:
set.Bind(foo).To(viewModel => viewModel.Bar);
then this tries to bind the default binding property on foo to the ViewModel's Bar property.
When you write:
set.Bind(foo).For(view => view.Zippy).To(viewModel => viewModel.Bar);
then this tries to bind the Zippy property on foo to the ViewModel's Bar property.
So, your line:
set.Bind(data_source.ItemsSource).To(viewModel => viewModel.GroupedVoiceMessages);
tries to bind an unknown property on the null ItemsSource to GroupedVoiceMessages
This obviously won't work - and there should be some warnings shown about the null in the trace.
Instead try:
set.Bind(data_source).For(v => v.ItemsSource).To(viewModel => viewModel.GroupedVoiceMessages);

Related

MvvmCross - Passing a string with IMvxNavigationService

I'm currently working on a Xamarin.iOS project that uses a web-api to gather data. However, I'm running into some problems trying to pass the user input from a textfield to the Tableview that gets the result from the api.
To do this I've followed the example on the MvvmCross documentation.
The problem is that the input from the Textfield never reaches the 'Filter' property in my TableviewController's viewmodel. I think I'm not passing the string object correctly to my IMvxNavigationService when called.
To clarify, in my UserinputViewController I'm binding the textfield's text like so:
[MvxFromStoryboard(StoryboardName = "Main")]
public partial class SearchEventView : MvxViewController
{
public SearchEventView (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
MvxFluentBindingDescriptionSet<SearchEventView, SearchEventViewModel> set = new MvxFluentBindingDescriptionSet<SearchEventView, SearchEventViewModel>(this);
set.Bind(btnSearch).To(vm => vm.SearchEventCommand);
set.Bind(txtSearchFilter).For(s => s.Text).To(vm => vm.SearchFilter);
set.Apply();
}
}
The Viewmodel linked to this ViewController looks like this:
public class SearchEventViewModel : MvxViewModel
{
private readonly IMvxNavigationService _navigationService;
private string _searchFilter;
public string SearchFilter
{
get { return _searchFilter; }
set { _searchFilter = value; RaisePropertyChanged(() => SearchFilter); }
}
public SearchEventViewModel(IMvxNavigationService mvxNavigationService)
{
this._navigationService = mvxNavigationService;
}
public IMvxCommand SearchEventCommand {
get {
return new MvxCommand<string>(SearchEvent);
}
}
private async void SearchEvent(string filter)
{
await _navigationService.Navigate<EventListViewModel, string>(filter);
}
}
And finally, TableviewController's viewmodel looks like this:
public class EventListViewModel : MvxViewModel<string>
{
private readonly ITicketMasterService _ticketMasterService;
private readonly IMvxNavigationService _navigationService;
private List<Event> _events;
public List<Event> Events
{
get { return _events; }
set { _events = value; RaisePropertyChanged(() => Events); }
}
private string _filter;
public string Filter
{
get { return _filter; }
set { _filter = value; RaisePropertyChanged(() => Filter); }
}
public EventListViewModel(ITicketMasterService ticketMasterService, IMvxNavigationService mvxNavigationService)
{
this._ticketMasterService = ticketMasterService;
this._navigationService = mvxNavigationService;
}
public IMvxCommand EventDetailCommand {
get {
return new MvxCommand<Event>(EventDetail);
}
}
private void EventDetail(Event detailEvent)
{
_navigationService.Navigate<EventDetailViewModel, Event>(detailEvent);
}
public override void Prepare(string parameter)
{
this.Filter = parameter;
}
public override async Task Initialize()
{
await base.Initialize();
//Do heavy work and data loading here
this.Events = await _ticketMasterService.GetEvents(Filter);
}
}
Whenever trying to run, the string object 'parameter' in my TableviewController's Prepare function remains 'null' and I have no idea how to fix it. Any help is greatly appreciated!
I believe the issue is with your command setup
new MvxCommand<string>(SearchEvent);
As this command is being bound to a standard UIButton. It will not pass through a parameter value of your filter but null instead. So the string parameter generic can be removed. Additionally, as you want to execute an asynchronous method I would suggest rather using MvxAsyncCommand
new MvxAsyncCommand(SearchEvent);
Then in terms of SearchEvent method you can remove the parameter. The value of filter is bound to your SearchFilter property. It is this property's value that you want to send as the navigation parameter.
private async Task SearchEvent()
{
await _navigationService.Navigate<EventListViewModel, string>(SearchFilter);
}

Wpf ICollectionView Binding item cannot resolve property of type object

I have bound a GridView with an ICollectionView in the XAML designer the properties are not known because the entity in the CollectionView have been transformed into type Object and the entity properties can't be accessed, it runs fine no error but the designer shows it as an error, if I bind to the collection I can access the properties fine
Example the entity is a Person with a string Name property I place them in an ObservableCollection<Person> and get the view from it and bind it to the GridView.ItemsSource now when I try to set the column header DataMemberBinding.FirstName property the designer shows it as an error
Cannot Resolve property 'FirstName' in data Context of type object
Is it a bug or is it Resharper playing tricks on me
Sample code:
public class Person
{
public string FirstName{
get { return _firstName; }
set { SetPropertyValue("FirstName", ref _firstName, value); }
}
}
public class DataService
{
public IDataSource DataContext { get; set; }
public ICollectionView PersonCollection{ get; set; }
public DataService()
{
DataContext = new DataSource();
//QueryableCollectionView is from Telerik
//but if i use any other CollectionView same thing
//DataContext Persons is an ObservableCollection<Person> Persons
PersonCollection = new QueryableCollectionView(DataContext.Persons);
}
}
<telerik:RadGridView x:Name="ParentGrid"
ItemsSource="{Binding DataService.PersonCollection}"
AutoGenerateColumns="False">
<telerik:RadGridView.Columns >
<telerik:GridViewDataColumn Header="{lex:Loc Key=FirstName}"
DataMemberBinding="{Binding FirstName}"/>
</telerik:RadGridView.Columns>
</telerik:RadGridView>
The warnings that Resharper is giving you in the XAML view is because the design-time view of the control does not know what type it's data-context is. You can use a d:DesignInstance to help with your bindings.
Add the following (replacing Assembly/Namespace/Binding Target names appropriately)
<UserControl x:Class="MyNamespace.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup‐compatibility/2006"
mc:Ignorable="d"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:lcl="clr‐namespace:MyAssembly"
d:DataContext="{d:DesignInstance Type=lcl:ViewModel}">
Your entity has not been transformed in object, it's because the interface ICollectionView is not a generic collection so ReSharper has no way to know that it holds a collection of Person.
You can create a generic version of ICollectionView and use it for your PersonCollection property as demonstrated in this post https://benoitpatra.com/2014/10/12/a-generic-version-of-icollectionview-used-in-a-mvvm-searchable-list/.
First some interfaces:
public interface ICollectionView<T> : IEnumerable<T>, ICollectionView
{
}
public interface IEditableCollectionView<T> : IEditableCollectionView
{
}
The implementation:
public class GenericCollectionView<T> : ICollectionView<T>, IEditableCollectionView<T>
{
readonly ListCollectionView collectionView;
public CultureInfo Culture
{
get => collectionView.Culture;
set => collectionView.Culture = value;
}
public IEnumerable SourceCollection => collectionView.SourceCollection;
public Predicate<object> Filter
{
get => collectionView.Filter;
set => collectionView.Filter = value;
}
public bool CanFilter => collectionView.CanFilter;
public SortDescriptionCollection SortDescriptions => collectionView.SortDescriptions;
public bool CanSort => collectionView.CanSort;
public bool CanGroup => collectionView.CanGroup;
public ObservableCollection<GroupDescription> GroupDescriptions => collectionView.GroupDescriptions;
public ReadOnlyObservableCollection<object> Groups => collectionView.Groups;
public bool IsEmpty => collectionView.IsEmpty;
public object CurrentItem => collectionView.CurrentItem;
public int CurrentPosition => collectionView.CurrentPosition;
public bool IsCurrentAfterLast => collectionView.IsCurrentAfterLast;
public bool IsCurrentBeforeFirst => collectionView.IsCurrentBeforeFirst;
public NewItemPlaceholderPosition NewItemPlaceholderPosition
{
get => collectionView.NewItemPlaceholderPosition;
set => collectionView.NewItemPlaceholderPosition = value;
}
public bool CanAddNew => collectionView.CanAddNew;
public bool IsAddingNew => collectionView.IsAddingNew;
public object CurrentAddItem => collectionView.CurrentAddItem;
public bool CanRemove => collectionView.CanRemove;
public bool CanCancelEdit => collectionView.CanCancelEdit;
public bool IsEditingItem => collectionView.IsEditingItem;
public object CurrentEditItem => collectionView.CurrentEditItem;
public event NotifyCollectionChangedEventHandler CollectionChanged
{
add => ((ICollectionView) collectionView).CollectionChanged += value;
remove => ((ICollectionView) collectionView).CollectionChanged -= value;
}
public event CurrentChangingEventHandler CurrentChanging
{
add => ((ICollectionView) collectionView).CurrentChanging += value;
remove => ((ICollectionView) collectionView).CurrentChanging -= value;
}
public event EventHandler CurrentChanged
{
add => ((ICollectionView) collectionView).CurrentChanged += value;
remove => ((ICollectionView) collectionView).CurrentChanged -= value;
}
public GenericCollectionView([NotNull] ListCollectionView collectionView)
{
this.collectionView = collectionView ?? throw new ArgumentNullException(nameof(collectionView));
}
public IEnumerator<T> GetEnumerator()
{
return (IEnumerator<T>) ((ICollectionView) collectionView).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((ICollectionView) collectionView).GetEnumerator();
}
public bool Contains(object item)
{
return collectionView.Contains(item);
}
public void Refresh()
{
collectionView.Refresh();
}
public IDisposable DeferRefresh()
{
return collectionView.DeferRefresh();
}
public bool MoveCurrentToFirst()
{
return collectionView.MoveCurrentToFirst();
}
public bool MoveCurrentToLast()
{
return collectionView.MoveCurrentToLast();
}
public bool MoveCurrentToNext()
{
return collectionView.MoveCurrentToNext();
}
public bool MoveCurrentToPrevious()
{
return collectionView.MoveCurrentToPrevious();
}
public bool MoveCurrentTo(object item)
{
return collectionView.MoveCurrentTo(item);
}
public bool MoveCurrentToPosition(int position)
{
return collectionView.MoveCurrentToPosition(position);
}
public object AddNew()
{
return collectionView.AddNew();
}
public void CommitNew()
{
collectionView.CommitNew();
}
public void CancelNew()
{
collectionView.CancelNew();
}
public void RemoveAt(int index)
{
collectionView.RemoveAt(index);
}
public void Remove(object item)
{
collectionView.Remove(item);
}
public void EditItem(object item)
{
collectionView.EditItem(item);
}
public void CommitEdit()
{
collectionView.CommitEdit();
}
public void CancelEdit()
{
collectionView.CancelEdit();
}
}
And finally the usage:
ICollectionView<Person> PersonCollectionView { get; }
In the constructor:
var view = (ListCollectionView) CollectionViewSource.GetDefaultView(PersonCollection);
PersonCollectionView = new GenericCollectionView<Person>(view);
Neither
d:DataContext="{d:DesignInstance Type=lcl:ViewModel}">
nor
GenericCollectionView
works directly for a DataGrid with a CollectionViewSource.
<DataGrid AutoGenerateColumns="False"
ItemsSource="{Binding collectionViewSource.View}"
SelectedItem="{Binding SelectedRow}"
We can't set "d:DataContext"; because, we often need to bind multiple properties to our viewmodel.
The CollectionViewSource creates new ListCollectionView which is runtime instantiated each time you set the Source property. Since setting the Source property is the only reasonable way to refresh a range of rows, we can't keep a GenericCollectionView around.
My solution is perhaps perfectly obvious, but I dumped the CollectionViewSource. By making creating a property
private ObservableCollection<ListingGridRow> _rowDataStoreAsList;
public GenericCollectionView<ListingGridRow> TypedCollectionView
{
get => _typedCollectionView;
set { _typedCollectionView = value; OnPropertyChanged();}
}
public void FullRefresh()
{
var listData = _model.FetchListingGridRows(onlyListingId: -1);
_rowDataStoreAsList = new ObservableCollection<ListingGridRow>(listData);
var oldView = TypedCollectionView;
var saveSortDescriptions = oldView.SortDescriptions.ToArray();
var saveFilter = oldView.Filter;
TypedCollectionView = new GenericCollectionView<ListingGridRow>(new ListCollectionView(_rowDataStoreAsList));
var newView = TypedCollectionView;
foreach (var sortDescription in saveSortDescriptions)
{
newView.SortDescriptions.Add(new SortDescription()
{
Direction = sortDescription.Direction,
PropertyName = sortDescription.PropertyName
});
}
newView.Filter = saveFilter;
}
internal void EditItem(object arg)
{
var view = TypedCollectionView;
var saveCurrentPosition = view.CurrentPosition;
var originalRow = view.TypedCurrentItem;
if (originalRow == null)
return;
var listingId = originalRow.ListingId;
var rawListIndex = _rowDataStoreAsList.IndexOf(originalRow);
// ... ShowDialog ... DialogResult ...
var lstData = _model.FetchListingGridRows(listingId);
_rowDataStoreAsList[rawListIndex] = lstData[0];
view.MoveCurrentToPosition(saveCurrentPosition);
view.Refresh();
}
After adding
public T TypedCurrentItem => (T)collectionView.CurrentItem;
To the GenericCollectionView provided by Maxence.

ItemsSource is empty in constructor of Custom Bound Horizontal ScrollView

I'm having trouble updating Cheesebarons horizontal list view to the new v3 MvvmCross. Everything seems to be working correctly except in the constructor of my "BindableHorizontalListView" control the ItemsSource of the adapter is null. Which is weird because the context shows that the view-model property I am attempting to bind to shows very clearly there are 3 items and the binding seems very straightforward. What am I missing? I hope I've included enough of the code. I've also tried binding it via fluent bindings on the "OnViewModelSet" event with the same result.
Warning presented
[MvxBind] 24.87 Unable to bind: source property source not found Cirrious.MvvmCross.Binding.Parse.PropertyPath.PropertyTokens.MvxPropertyNamePropertyToken on DeviceViewModel
AXML
<BindableHorizontalListView
android:id="#+id/listView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
local:MvxBind="ItemsSource DevicesList; ItemClick ItemSelected"
local:MvxItemTemplate="#layout/devices_horizontal_list_item" />
BindableHorizontalListView control
using System.Collections;
using System.Windows.Input;
using Android.Content;
using Android.Util;
using Cirrious.MvvmCross.Binding.Attributes;
using Cirrious.MvvmCross.Binding.Droid.Views;
namespace Project.Droid.Controls
{
public class BindableHorizontalListView
: HorizontalListView //Which inherits from AdapterView<BaseAdapter>
{
public BindableHorizontalListView(Context context, IAttributeSet attrs)
: this(context, attrs, new MvxAdapter(context))
{
}
public BindableHorizontalListView(Context context, IAttributeSet attrs, MvxAdapter adapter)
: base(context, attrs)
{
InitView ();
var itemTemplateId = MvxAttributeHelpers.ReadListItemTemplateId (context, attrs);
adapter.ItemTemplateId = itemTemplateId;
Adapter = adapter;
SetupItemClickListener();
}
public new MvxAdapter Adapter
{
get { return base.Adapter as MvxAdapter; }
set
{
var existing = Adapter;
if (existing == value)
return;
if (existing != null && value != null)
{
value.ItemsSource = existing.ItemsSource;
value.ItemTemplateId = existing.ItemTemplateId;
}
base.Adapter = value;
}
}
[MvxSetToNullAfterBinding]
public IEnumerable ItemsSource
{
get { return Adapter.ItemsSource; }
set { Adapter.ItemsSource = value; this.Reset (); }
}
public int ItemTemplateId
{
get { return Adapter.ItemTemplateId; }
set { Adapter.ItemTemplateId = value; }
}
public new ICommand ItemClick { get; set; }
private void SetupItemClickListener()
{
base.ItemClick += (sender, args) =>
{
if (null == ItemClick)
return;
var item = Adapter.GetItem(args.Position) as Java.Lang.Object;
if (item == null)
return;
if (item == null)
return;
if (!ItemClick.CanExecute(item))
return;
ItemClick.Execute(item);
};
}
}
}
View
[Activity (Label = "Device", ScreenOrientation = ScreenOrientation.Portrait)]
public class DeviceView : MvxActivity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView(Resource.Layout.device);
}
}
Property on ViewModel
private Services.Device[] _devicesList;
public Services.Device[] DevicesList {
get {
return _devicesList;
}
set {
_devicesList = value;
RaisePropertyChanged(() => DevicesList);
}
}
If only there was PCL support in XAM STUDIO I would just step in and see how the other controls are doing it!!!!
ItemsSource will always be empty in the constructor - it's a property which is set by binding, and that property can only be set after the constructor has completed.
The message:
[MvxBind] 24.87 Unable to bind: source property source not found Cirrious.MvvmCross.Binding.Parse.PropertyPath.PropertyTokens.MvxPropertyNamePropertyToken on DeviceViewModel
contains a bug - fixed in a recent commit - so the message should be more readable in the future.
If the bug hadn't been there, I suspect the message would say that the problem is in DevicesList - the binding can't find that property. Is it there? Does it have a get? Is it public?

Caliburn Micro: how to navigate in Windows phone silverlight

i am trying to use Caliburn Micro in my windows phone 7 project.
But i got a nullreferenceexception when navigate the page.
namespace Caliburn.Micro.HelloWP7 {
public class MainPageViewModel {
readonly INavigationService navigationService;
public MainPageViewModel(INavigationService navigationService) {
this.navigationService = navigationService;
}
public void GotoPageTwo() {
/*navigationService.UriFor<PivotPageViewModel>()
.WithParam(x => x.NumberOfTabs, 5)
.Navigate();*/
navigationService.UriFor<Page1ViewModel>().Navigate();
}
}
}
namespace Caliburn.Micro.HelloWP7
{
public class Page1ViewModel
{
readonly INavigationService navigationService;
public Page1ViewModel(INavigationService navigationService)
{
this.navigationService = navigationService;
}
}
}
can anyone tell me what's the problem of my code? thanks in advance.
here is bootstrapper:
public class ScheduleBootstrapper : PhoneBootstrapper
{
PhoneContainer container;
protected override void Configure()
{
container = new PhoneContainer(RootFrame);
container.RegisterPhoneServices();
container.PerRequest<MainPageViewModel>();
container.PerRequest<MainContentViewModel>();
container.PerRequest<Page1ViewModel>();
AddCustomConventions();
}
static void AddCustomConventions()
{
ConventionManager.AddElementConvention<Pivot>(Pivot.ItemsSourceProperty, "SelectedItem", "SelectionChanged").ApplyBinding =
(viewModelType, path, property, element, convention) =>
{
if (ConventionManager
.GetElementConvention(typeof(ItemsControl))
.ApplyBinding(viewModelType, path, property, element, convention))
{
ConventionManager
.ConfigureSelectedItem(element, Pivot.SelectedItemProperty, viewModelType, path);
ConventionManager
.ApplyHeaderTemplate(element, Pivot.HeaderTemplateProperty, viewModelType);
return true;
}
return false;
};
ConventionManager.AddElementConvention<Panorama>(Panorama.ItemsSourceProperty, "SelectedItem", "SelectionChanged").ApplyBinding =
(viewModelType, path, property, element, convention) =>
{
if (ConventionManager
.GetElementConvention(typeof(ItemsControl))
.ApplyBinding(viewModelType, path, property, element, convention))
{
ConventionManager
.ConfigureSelectedItem(element, Panorama.SelectedItemProperty, viewModelType, path);
ConventionManager
.ApplyHeaderTemplate(element, Panorama.HeaderTemplateProperty, viewModelType);
return true;
}
return false;
};
}
protected override object GetInstance(Type service, string key)
{
return container.GetInstance(service, key);
}
protected override IEnumerable<object> GetAllInstances(Type service)
{
return container.GetAllInstances(service);
}
protected override void BuildUp(object instance)
{
container.BuildUp(instance);
}
}
I had this too, and tracked it down as follows:
As you know, Caliburn.Micro uses convention-over-configuration to locate Views for ViewModels, and vice-versa, which means we need to follow the conventions. My mistake was to have the namespace's inconsistent for the View and ViewModel
In my case, I had
MyWP7App.DetailsViewModel, and
MyWP7App.Views.DetailsView
--> I renamed the VM's namespace to be MyWP7App.ViewModels.DetailsViewModel, and it worked out fine. I think I could have moved the view into MyWP7App.DetailsView for a good result, too...
Under the covers
the call to Navigate() invokes DeterminePageName() which, in turn, invokes ViewLocator.LocateTypeForModelType
This, like the rest of CM is overridable, but the default implementation looks like this:
public static Func<Type, DependencyObject, object, Type> LocateTypeForModelType = (modelType, displayLocation, context) => {
var viewTypeName = modelType.FullName.Substring(
0,
modelType.FullName.IndexOf("`") < 0
? modelType.FullName.Length
: modelType.FullName.IndexOf("`")
);
Func<string, string> getReplaceString;
if (context == null) {
getReplaceString = r => { return r; };
}
else {
getReplaceString = r => {
return Regex.Replace(r, Regex.IsMatch(r, "Page$") ? "Page$" : "View$", ContextSeparator + context);
};
}
var viewTypeList = NameTransformer.Transform(viewTypeName, getReplaceString);
var viewType = (from assembly in AssemblySource.Instance
from type in assembly.GetExportedTypes()
where viewTypeList.Contains(type.FullName)
select type).FirstOrDefault();
return viewType;
};
If you follow the debugger through, you end up with a collection viewTypeList that contains MyWP7App.DetailsView, and a type whose full name is MyWP7App.Views.DetailsView, and the viewType returned is therefore null... this is the cause of the NullReferenceException.
I'm 99% sure the NameTransformer.Transform call will perform a pattern-match and transform the ViewModels in the namespace of the VM to Views in the namespace of the View it's trying to locate...

DataGridView List<T> column?

I have a datagridView, that is bound to a List. This List is made up of my class which contains 2 public properties, a String Name, and another List CustomList. See below:
public class MyClass2
{
public string Name
{ get; set;}
public string Description
{
get;
set;
}
}
public class MyClass
{
List<MyClass2> myList;
public string Name
{
get;
set;
}
public List<MyClass2> CustomList
{
get { return myList ?? (myList= new List<MyClass2>()); }
}
}
And then in my designer page:
List<MyClass> myClassList = new List<MyClass>();
dataGridView.DataSource = myClassList;
As it is right now, the only column that appears in the grid, is the MyClass:Name column, and the CustomList column does not show up. What I'd like is the CustomList column to show and to display something like "Collection" with the "..." button showing, and when it is clicked to have the "Collection Editor" to popup.
Does anyone know if this is possible and how to enable it? If there's a tutorial or anything that would help me out I'd appreciate that too. Thanks.
Using generics, I think, is a clean solution:
public class Sorter<T>: IComparer<T>
{
public string Propiedad { get; set; }
public Sorter(string propiedad)
{
this.Propiedad = propiedad;
}
public int Compare(T x, T y)
{
PropertyInfo property = x.GetType().GetProperty(this.Propiedad);
if (property == null)
throw new ApplicationException("El objeto no tiene la propiedad " + this.Propiedad);
return Comparer.DefaultInvariant.Compare(property.GetValue(x, null), property.GetValue(y, null));
}
}
Usage example:
string orderBy = "propertyName";
bool orderAsc = true;
List<MyExampleClass> myClassList = someMethod();
if (!string.IsNullOrEmpty(orderBy))
{
myClassList.Sort(new Sorter<MyExampleClass>(orderBy));
if (!orderAsc) myClassList.Reverse();
}
Short answer: Yes, you can do it with some code.
Long answer: To write the code is gonna be a pain in the ass, as you would have to know not only how the DataGridView behaves with custom columns, but you would need to know how to expose design time elements at runtime, which requires quite a bit of plumbing. Extensive knowledge about the PropertyGrid must also be known.
Note: This might a fun component to write. (I might actually tackle it if I get some time)
So using the 'button' approach posted by Dave, and some code that I found that implements the CollectionEditor, I can edit the CustomList in MyClass2
Here's my solution, although not quite as clean as I'd like:
Put this class somewhere:
class MyHelper : IWindowsFormsEditorService, IServiceProvider, ITypeDescriptorContext
{
public static void EditValue(IWin32Window owner, object component, string propertyName)
{
PropertyDescriptor prop = TypeDescriptor.GetProperties(component)[propertyName];
if (prop == null) throw new ArgumentException("propertyName");
UITypeEditor editor = (UITypeEditor)prop.GetEditor(typeof(UITypeEditor));
MyHelper ctx = new MyHelper(owner, component, prop);
if (editor != null && editor.GetEditStyle(ctx) == UITypeEditorEditStyle.Modal)
{
object value = prop.GetValue(component);
value = editor.EditValue(ctx, ctx, value);
if (!prop.IsReadOnly)
{
prop.SetValue(component, value);
}
}
}
private readonly IWin32Window owner;
private readonly object component;
private readonly PropertyDescriptor property;
private MyHelper(IWin32Window owner, object component, PropertyDescriptor property)
{
this.owner = owner;
this.component = component;
this.property = property;
}
#region IWindowsFormsEditorService Members
public void CloseDropDown()
{
throw new NotImplementedException();
}
public void DropDownControl(System.Windows.Forms.Control control)
{
throw new NotImplementedException();
}
public System.Windows.Forms.DialogResult ShowDialog(System.Windows.Forms.Form dialog)
{
return dialog.ShowDialog(owner);
}
#endregion
#region IServiceProvider Members
public object GetService(Type serviceType)
{
return serviceType == typeof(IWindowsFormsEditorService) ? this : null;
}
#endregion
#region ITypeDescriptorContext Members
IContainer ITypeDescriptorContext.Container
{
get { return null; }
}
object ITypeDescriptorContext.Instance
{
get { return component; }
}
void ITypeDescriptorContext.OnComponentChanged()
{ }
bool ITypeDescriptorContext.OnComponentChanging()
{
return true;
}
PropertyDescriptor ITypeDescriptorContext.PropertyDescriptor
{
get { return property; }
}
#endregion
Add a button column to the data grid:
DataGridViewButtonColumn butt = new DataGridViewButtonColumn();
butt.HeaderText = "CustomList";
butt.Name = "CustomList";
butt.Text = "Edit CustomList...";
butt.UseColumnTextForButtonValue = true;
dataGridView.Columns.Add(butt);
dataGridView.CellClick += new DataGridViewCellEventHandler(dataGridView_CellClick);
Then call it in the button handler of the cell click.
if (e.RowIndex < 0 || e.ColumnIndex != dataGridView.Columns["CustomList"].Index)
return;
//get the name of this column
string name = (string)dataGridView[dataGridView.Columns["Name"].Index, e.RowIndex].Value;
var myClassObject= myClassList.Find(o => o.Name == name);
MyHelper.EditValue(this, myClassObject, "CustomList");
I'd still be interested in hearing other approaches, and not having to implement my own CollectionEditor. And I'm still interested in having it look more like what the TabControl uses to add TabPages in the PropertyGrid...by displaying the "..." button...but this might work for now.
What you want to do is add a column template with a button in it:
http://geekswithblogs.net/carmelhl/archive/2008/11/11/126942.aspx
In the handler for the button, get the selected MyClass item from the collection and bind its list property to a grid in your popup.

Categories

Resources