DataContextProxy silverlight comboboxes - is there a better way? - c#

I'm using the datacontextproxy class defined by Dan Wahlin to solve what seemed so very difficult for the many many hours leading up to that discovery.
I have a combobox that is bound to an ObservableCollection<Accounts>. The combobox also has the values: DisplayMemberPath=AccountNumber, and the SelectedValue={Binding SelectedAccount}. I then have a DataForm that has its CurrentItem property also bound to SelectedAccount. Inside my DataForm, I have a handful of fields that require additional dropdowns (AcctCode, UsageCode, etc). To mitigate the binding issues I ran into inside of a DataForm, I implemented the datacontextproxy, allowing me to set the ItemsSource of my cbobox to {Binding Source={StaticResource DataContextProxy}, Path=DataSource.AccountCodes}". This is working great in terms of the end result.
Before stumbling onto this, I really struggled with this find. I'm not using a domaincontext, so I couldn't use Kyle Mcllelans ComboBoxex, nor could I use the vast majority of solutions offered. I did try to create an instance of my ViewModel as a local resource in my View, but a) I felt dirty in terms of MVVM, and b) It failed to create a new VM instance, as my VM requires a number of service references to be passed in on construct.
In any case, I'm simply wondering if there's a way I should be doing this that's either more performant, more MVVM, more maintainable, more bestest'er, etc etc.
Thanks,
Scott

Scott I also have settled on using the DataContextProxy. I think use of it still provides a good MVVM solution where the view only has knowledge of the VM via binding or commanding.
I see use of it as a temporary solution until Silverlight 5 ships. In Silverlight 5 ancestor binding is introduced which will provide more flexibility in data binding.

Related

Data Binding and UI

I need your opinion about UI and Databinding in WPF.
I had argue with my supervisor about UI & databinding. There is A class, it has ObservableCollection of B class, and B class also has ObservableCollection of C class. These classes are used while communicating with NI CAN and LIN device(it is not case).
On the other hand, in user interface there are bunches of TreeView and DataGrids. There are several instances of A class which is used to store data from devices and files, and they are binded to Treeview and Datagrids. But, he disagrees with this, and says to make separate other list of variables for TreeView and Datagrid to data binding. As he says UI data and other must be separate and I agree with it. But, in this case there are several lists of lists of lists and for example: copy from one list to other list when there is change on data takes much time and calculation ( -> UI element ). And other problems also.
I need your your opinion or other advice to come out better solution.
Thank you!!
It sounds like you are a student and doing this work as part of your studies. Either way, there is something to learn here.
Why not implement both approaches and see how they differ, and which you prefer? As it stands your question does not provide enough information for anyone else to tell you, and there is no way to short cut this kind of learning in my experience.

Dynamically create a class and then create a list<dynamicClass> based on it in C#

I want to create a class and its properties on run time, the properties will be like Year2001, Year2002, Year2003, Year2004, Year2005... I get these property names on run-time, I get them in a list. Later I need to use this class to create a list which I need to show in the kendo grid.I surfed a lot and thought of using ExpandoObject, but was unsuccessful.
If all properties will be of the form YearX and contain some information about or related to that year, then I would strongly recommend you (if at all possible) to go with something along the lines of an IList<YearInfo> where YearInfo is some object containing the info you need for every year, including an integer property indicating what year the object corresponds to. If you require these objects to be unique you could use an IDictionary<int, YearObject> or ISet<YearObject> instead.
Reflection can be powerful, but it it comes at the price of complexity and loss of type safety/compile-time checks. Avoid when possible.
Sounds to me like you are really wanting to a grid with grouping support. Your idea of having the system create a CLASS at runtime is not going to fly. Even if it were possible, which I doubt it is, it is absolutely the wrong approach.
Like I say - have a read about Grouping / Hierarchy on Grid Controls (Kendo grid example here), and maybe have a look at OLAP cubes as well...
Although you have had some answers I would also like to suggest an alternative way of doing this which is using DataTables. This is the approach I take when I have any "Dynamic" data sets that I want to present to the grid.
This is also the approach that Telerik themselves take with one of their code samples.
here are a couple of links to show them doing this to DataTables and Dynamic Objects
Grid Binding to Data Table
Grid Binding to Dynamic Objects
Personally I find the binding to Tables easier to deal with as I am used to dealing with Data Tables.

Binding to a Binding: Data Binding indirection -or- Metabinding in WPF

No way to explain this issue except by example:
Say you have a custom UserControl with two DependencyPropertys, StatList Stats and string ImportantStat. The job of the user control is to display a table showing all of the values in Stats but with special visual treatment (like a pie chart) of the ImportantStat.
My instinct was to write a block of XAML that looked more or less like:
<PieChart Value="{Binding Path={Binding ImportantStat} }"/>
where the DataContext is prior set to Stats. So, the user passes in ImportantStat = "WinPercentage" and the pie chart binds to the WinPercentage Property of the stat line. But the user can just as easily pick some other Property to emphasize.
The problem (of course, you already know this, educated Stacker) is that you get an error message stating that you can't convert from Binding to string, which is what the outer Binding expects for Path. Though I haven't proven it to myself, I am guessing this is simply because Path is not a DependencyProperty.
So, is there any way to achieve my goal here? Feel free to break my assumptions in that first paragraph. Maybe, for example, ImportantStat can't be a string but must itself be a Binding.
Edit: Attempt #1 Failed
I was hoping that exposing from the code-behind a new DependencyProperty Binding ImportantStatBinding would allow me to rewrite the XAML as:
<PieChart Value="{Binding ImportantStatBinding, RelativeSource=... }"/>
...but to no avail. The indirect Binding is just stuck into Value itself with no attempts to resolve it.
My backup solution, which might be where this is headed, will be to just create the content inside the code-behind where I have access to ImportantStat directly and so can get away with a single Binding.
Far as I know, there is no way to concatenate data bindings in this way, without additional code. To put the problem more simply, we can have data binding (of course) of the form:
A --> B --> C
but you cannot have data binding of the form:
A --> B --> *A (*A indicates the target depends on the value of A)
because the relationships must be fixed.
It seems like it might be possible to create a Converter whose job is to convert a string into an arbitrary value by actually dereferencing a Binding using some additional context and that string as the property path. That sounds messy with type issues, so I chose the only other way I could think of:
I added a new DependencyProperty for the PieChart to the code behind and made sure that I constructed it at the appropriate times, so that the XAML could consume it. It's ugly, but it works. I just feel a little dead inside :) Hope someone finds this useful some day.

WP7 - Data bound value in custom control, how to set default string so it's visible in designer

I'm fairly new to WP7 and totally new to Expression Blend.
I have a ListBox bound to a List of custom objects,
List<Person>
Each item in the list contains a custom control, MyControl which is bound to Person.
MyControl contains a TextBox which is bound to the Username property of Person.
All of this works fine. My question is: how do I set a default value for the TextBlock so that it becomes visible in the Designer or ExpressionBlend? With it being data bound, it has no text till it runs ... so I can't actually do any fancy styling using these wonderful tools unless I repeatedly delete the binding code to replace it with a string, make the changes, replace the binding code, repeat. Seems long winded!
Thanks,
Steven
What you want is "Design time data".
There are a number of ways of doing this. Fortunately there are also lots of resources online which explain it.
#Steven Have you looked at creating sample data in Blend to do what you require and then some binding to actually attached the data to the control bound to your list? You might like to check out Blend Sample Data as it guides you through a simple example of doing just that. You might then be able to adapt to to your own ends.
It depends if you are using any MVVM model or not.
My suggestion, if you are not using a MVVM, is to use Blend Sample data, is fast and quick.
If you are MVVM Light I've found very usefull to create two files:
DataService.cs - contains the real connection and data
DesignDataService.cs - contains the sample data
The two libraries are identical, from an call perspective so that in the ViewModelLocator you can swap them:
if (ViewModelBase.IsInDesignModeStatic)
{
SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();
}
else
{
//SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();
SimpleIoc.Default.Register<IDataService, DataService>();
}
In the Design class I've decided to create an XML file for each Model so that it's easy to change the sample data and test all possible scenarios.
I then use the Deserialize function to read it:
csNodeList _Copyrights = new csNodeList();
resource = System.Windows.Application.GetResourceStream(new Uri(#"Design/sampledata.xml", UriKind.Relative));
streamReader = new StreamReader(resource.Stream);
serializer = new XmlSerializer(typeof(csNodeList));
_Copyrights = (csNodeList)serializer.Deserialize(streamReader);
Please note that the file sampledata.xml has to be stored in folder Design and must be defined as Content not as Resource.
It is suggested to improve performance and load time.
M

Silverlight and icollectionview

So I have a datagrid that I need to add custom sorting for and I also need to know the exact order of the sort.
I have read in order to do this I need to implement a custom icollectionview and bind it to the datagrid.
The problem I am having is that the documentation Microsoft gives on this interface is not that great. Does anyone know how to do this or have any good tutorials on how to implement this interface for silverlight?
I'm looking for the same, and found this article from Colin Eberhardt. It shows how to implement sorting using an implementation of ICollectionView
If you figure out how to implement filtering, please let me know.
Silverlight 3 now supports and implementation of the ICollectionView, called PagedCollectionView.
This provides sorting and grouping, but not filtering.
The best example I've found is Microsoft's ICollectionView implementation that was created for use with the DataGrid. Unfortunately, they tagged it internal so you can't just use it outright (and a copy & paste of the source requires a few modifications). Bust out Reflector and open System.Windows.Controls.Data.dll - navigate to the System.Windows.Controls namespace and there you can find ListCollectionView. Here's the definition to show that it implements ICollectionView:
internal class ListCollectionView : ICollectionView, INotifyCollectionChanged, INotifyPropertyChanged, IEnumerable
...
I really wish MS would provide this class - practically every LOB app needs it.
Here's how you perform a sort using ICollectionView.
ICollectionView view = CollectionViewSource.GetDefaultView(someCollection);
view.SortDescriptions.Add(new SortDescription("someProperty", ListSortDirection.Ascending));
view.SortDescriptions.Add(new SortDescription("someOtherProperty", ListSortDirection.Descending));
However it's not exactly what I would call "custom sorting"... It just lets you choose the sort criteria and direction. Could you be more specific on what you want to do ?
For other's who browse to this question, I've found these sites helpful as well:
Silverlight 3 Custom Sorting with Paging Support - Manish Dalal's blog
ICollectionView explained « C# Disciples
I hope that Silverlight 5 has a better alternative. :)

Categories

Resources