Search Results

Search found 369 results on 15 pages for 'observablecollection'.

Page 4/15 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Do i *have* to use ObservableCollection in Silverlight WCF client?

    - by Simon_Weaver
    When accessing Silverlight in WCF you get proxies generated with ObservableCollection Thats fine when you're databinding, but a little clumsy when you're just calling a method. For instance the following service method : [OperationContract] public SearchOrdersMsgOut SearchOrders(ShippingStatusType[] shippingStatuses, string[] orderId) { } gets generated with ObservableCollection. What! They're just parameters. Why would I ever want to 'observe' them? I'm fine if I have to do this - but it seems like there should be a way to force simple array structures when I know I'm never databinding - especially on input messages. I'd much rather do this : searchCriteria.PaymentStatus = new [] { PaymentStatusType.PaymentFailed, PaymentStatusType.Unpaid }; than this : searchCriteria.PaymentStatus = new ObservableCollection<PaymentStatusType> { PaymentStatusType.PaymentFailed, PaymentStatusType.Unpaid }; Is there a way? PS. I do actually use a SearchCriteria object for my search criteria - but I simplified for this example wondering if parameters were handled differently.

    Read the article

  • How to make TwoWay binding on properties of ObservableCollection of custom class using mvvm pattern?

    - by mill
    I have the following class: public class UserGroup { public string GroupName { get; set; } public bool IsIntheGroup{ get; set; } } I want to bind an ObservableCollection of UserGroup items to listbox containing checkbox’s for each item in the collection and the checkbox is cheked based on the IsIntheGroup property of the UserGroup. In my ViewModel I made an ObservableCollection of the UserGroup class: public ObservableCollection Groups { get; set; } and loaded its contents (instances of UserGroup) from my database model I used the following code in my view: ListBox ItemsSource="{Binding Groups, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" ListBox.ItemTemplate DataTemplate StackPanel Orientation="Horizontal" CheckBox IsChecked="{Binding IsIntheGroup, Mode=TwoWay}"/ TextBlock Text="{Binding GroupName}" / /StackPanel /DataTemplate /ListBox.ItemTemplate /ListBox The problem is I am not notified when the user checks/unchecks a check box in the list so my two way binding failed… How do I do a two way binding in such a case?

    Read the article

  • WCF RIA Services DomainContext Abstraction Strategies–Say That 10 Times!

    - by dwahlin
    The DomainContext available with WCF RIA Services provides a lot of functionality that can help track object state and handle making calls from a Silverlight client to a DomainService. One of the questions I get quite often in our Silverlight training classes (and see often in various forums and other areas) is how the DomainContext can be abstracted out of ViewModel classes when using the MVVM pattern in Silverlight applications. It’s not something that’s super obvious at first especially if you don’t work with delegates a lot, but it can definitely be done. There are various techniques and strategies that can be used but I thought I’d share some of the core techniques I find useful. To start, let’s assume you have the following ViewModel class (this is from my Silverlight Firestarter talk available to watch online here if you’re interested in getting started with WCF RIA Services): public class AdminViewModel : ViewModelBase { BookClubContext _Context = new BookClubContext(); public AdminViewModel() { if (!DesignerProperties.IsInDesignTool) { LoadBooks(); } } private void LoadBooks() { _Context.Load(_Context.GetBooksQuery(), LoadBooksCallback, null); } private void LoadBooksCallback(LoadOperation<Book> books) { Books = new ObservableCollection<Book>(books.Entities); } } Notice that BookClubContext is being used directly in the ViewModel class. There’s nothing wrong with that of course, but if other ViewModel objects need to load books then code would be duplicated across classes. Plus, the ViewModel has direct knowledge of how to load data and I like to make it more loosely-coupled. To do this I create what I call a “Service Agent” class. This class is responsible for getting data from the DomainService and returning it to a ViewModel. It only knows how to get and return data but doesn’t know how data should be stored and isn’t used with data binding operations. An example of a simple ServiceAgent class is shown next. Notice that I’m using the Action<T> delegate to handle callbacks from the ServiceAgent to the ViewModel object. Because LoadBooks accepts an Action<ObservableCollection<Book>>, the callback method in the ViewModel must accept ObservableCollection<Book> as a parameter. The callback is initiated by calling the Invoke method exposed by Action<T>: public class ServiceAgent { BookClubContext _Context = new BookClubContext(); public void LoadBooks(Action<ObservableCollection<Book>> callback) { _Context.Load(_Context.GetBooksQuery(), LoadBooksCallback, callback); } public void LoadBooksCallback(LoadOperation<Book> lo) { //Check for errors of course...keeping this brief var books = new ObservableCollection<Book>(lo.Entities); var action = (Action<ObservableCollection<Book>>)lo.UserState; action.Invoke(books); } } This can be simplified by taking advantage of lambda expressions. Notice that in the following code I don’t have a separate callback method and don’t have to worry about passing any user state or casting any user state (the user state is the 3rd parameter in the _Context.Load method call shown above). public class ServiceAgent { BookClubContext _Context = new BookClubContext(); public void LoadBooks(Action<ObservableCollection<Book>> callback) { _Context.Load(_Context.GetBooksQuery(), (lo) => { var books = new ObservableCollection<Book>(lo.Entities); callback.Invoke(books); }, null); } } A ViewModel class can then call into the ServiceAgent to retrieve books yet never know anything about the DomainContext object or even know how data is loaded behind the scenes: public class AdminViewModel : ViewModelBase { ServiceAgent _ServiceAgent = new ServiceAgent(); public AdminViewModel() { if (!DesignerProperties.IsInDesignTool) { LoadBooks(); } } private void LoadBooks() { _ServiceAgent.LoadBooks(LoadBooksCallback); } private void LoadBooksCallback(ObservableCollection<Book> books) { Books = books } } You could also handle the LoadBooksCallback method using a lambda if you wanted to minimize code just like I did earlier with the LoadBooks method in the ServiceAgent class.  If you’re into Dependency Injection (DI), you could create an interface for the ServiceAgent type, reference it in the ViewModel and then inject in the object to use at runtime. There are certainly other techniques and strategies that can be used, but the code shown here provides an introductory look at the topic that should help get you started abstracting the DomainContext out of your ViewModel classes when using WCF RIA Services in Silverlight applications.

    Read the article

  • Why does ObservableCollection throws an exception when being modified?

    - by Oliver Hanappi
    Hi! My application uses a WPF DataGrid. One of the columns is a template column that containts a combobox bound to an ObservableCollection of the entity which feeds the row. When I add a value to the ObservableCollection, a NullReferenceException is thrown. Has anybody an idea why this happens? Here is the stacktrace of the exception: at MS.Internal.Data.PropertyPathWorker.DetermineWhetherDBNullIsValid() at MS.Internal.Data.PropertyPathWorker.get_IsDBNullValidForUpdate() at MS.Internal.Data.ClrBindingWorker.get_IsDBNullValidForUpdate() at System.Windows.Data.BindingExpression.ConvertProposedValue(Object value) at System.Windows.Data.BindingExpressionBase.UpdateValue() at System.Windows.Data.BindingExpression.Update(Boolean synchronous) at System.Windows.Data.BindingExpressionBase.Dirty() at System.Windows.Data.BindingExpression.SetValue(DependencyObject d, DependencyProperty dp, Object value) at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, OperationType operationType, Boolean isInternal) at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value) at System.Windows.Controls.Primitives.Selector.UpdatePublicSelectionProperties() at System.Windows.Controls.Primitives.Selector.SelectionChanger.End() at System.Windows.Controls.Primitives.Selector.OnItemsChanged(NotifyCollectionChangedEventArgs e) at System.Windows.Controls.ItemsControl.OnItemCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e) at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e) at System.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args) at System.Windows.Controls.ItemCollection.System.Windows.IWeakEventListener.ReceiveWeakEvent(Type managerType, Object sender, EventArgs e) at System.Windows.WeakEventManager.DeliverEventToList(Object sender, EventArgs args, ListenerList list) at System.Windows.WeakEventManager.DeliverEvent(Object sender, EventArgs args) at System.Collections.Specialized.CollectionChangedEventManager.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args) at System.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args) at System.Windows.Data.ListCollectionView.ProcessCollectionChangedWithAdjustedIndex(NotifyCollectionChangedEventArgs args, Int32 adjustedOldIndex, Int32 adjustedNewIndex) at System.Windows.Data.ListCollectionView.ProcessCollectionChanged(NotifyCollectionChangedEventArgs args) at System.Windows.Data.CollectionView.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args) at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item) at System.Collections.ObjectModel.Collection`1.Add(T item) at ORF.PersonBook.IdentityModule.Model.SubsidiaryModel.AddRoom(RoomModel room) in C:\Project\Phoenix\Development\src\ORF.PersonBook.IdentityModule\Model\SubsidiaryModel.cs:line 127

    Read the article

  • How do i bind my ObservableCollection<T> object in my codebehind to my listbox... Silverlight WP7

    - by Nawaz Dhandala
    This is My codebehind public System.Collections.ObjectModel.ObservableCollection FriendList { get; set; } // I want to bind this to my listbox public Friends() //this is constructor { InitializeComponent(); this.DataContext = this; //I think this is what I'm doing is right....:) } How do I bind my FriendList to the ListBox - FriendList has a property of user.UserName which I want to display it in the TextBlock "friendUsername" Please help!!! Thanks for your answers!!!

    Read the article

  • WPF DataContext does not refresh the DataGrid using MVVM model

    - by vikram bhatia
    Project Overview I have a view which binds to a viewmodel containing 2 ObserverableCollection. The viewmodel constructor populates the first ObserverableCollection and the view datacontext is collected to bind to it through a public property called Sites. Later the 2ed ObserverableCollection is populated in the LoadOrders method and the public property LoadFraudResults is updated for binding it with datacontext. I am using WCF to pull the data from the database and its getting pulled very nicely. VIEWMODEL SOURCE class ManageFraudOrderViewModel:ViewModelBase { #region Fields private readonly ICollectionView collectionViewSites; private readonly ICollectionView collectionView; private ObservableCollection<GeneralAdminService.Website> _sites; private ObservableCollection<FraudService.OrderQueue> _LoadFraudResults; #endregion #region Properties public ObservableCollection<GeneralAdminService.Website> Sites { get { return this._sites; } } public ObservableCollection<FraudService.OrderQueue> LoadFraudResults { get { return this._LoadFraudResults;} } #endregion public ManageFraudOrderViewModel() { //Get values from wfc service model GeneralAdminService.GeneralAdminServiceClient generalAdminServiceClient = new GeneralAdminServiceClient(); GeneralAdminService.Website[] websites = generalAdminServiceClient.GetWebsites(); //Get values from wfc service model if (websites.Length > 0) { _sites = new ObservableCollection<Wqn.Administration.UI.GeneralAdminService.Website>(); foreach (GeneralAdminService.Website website in websites) { _sites.Add((Wqn.Administration.UI.GeneralAdminService.Website)website); } this.collectionViewSites= CollectionViewSource.GetDefaultView(this._sites); } generalAdminServiceClient.Close(); } public void LoadOrders(Wqn.Administration.UI.FraudService.Website website) { //Get values from wfc service model FraudServiceClient fraudServiceClient = new FraudServiceClient(); FraudService.OrderQueue[] OrderQueue = fraudServiceClient.GetFraudOrders(website); //Get values from wfc service model if (OrderQueue.Length > 0) { _LoadFraudResults = new ObservableCollection<Wqn.Administration.UI.FraudService.OrderQueue>(); foreach (FraudService.OrderQueue orderQueue in OrderQueue) { _LoadFraudResults.Add(orderQueue); } } this.collectionViewSites= CollectionViewSource.GetDefaultView(this._LoadFraudResults); fraudServiceClient.Close(); } } VIEW SOURCE public partial class OrderQueueControl : UserControl { private ManageFraudOrderViewModel manageFraudOrderViewModel ; private OrderQueue orderQueue; private ButtonAction ButtonAction; private DispatcherTimer dispatcherTimer; public OrderQueueControl() { LoadOrderQueueForm(); } #region LoadOrderQueueForm private void LoadOrderQueueForm() { //for binding the first observablecollection manageFraudOrderViewModel = new ManageFraudOrderViewModel(); this.DataContext = manageFraudOrderViewModel; } #endregion private void cmbWebsite_SelectionChanged(object sender, SelectionChangedEventArgs e) { BindItemsSource(); } #region BindItemsSource private void BindItemsSource() { using (OverrideCursor cursor = new OverrideCursor(Cursors.Wait)) { if (!string.IsNullOrEmpty(Convert.ToString(cmbWebsite.SelectedItem))) { Wqn.Administration.UI.FraudService.Website website = (Wqn.Administration.UI.FraudService.Website)Enum.Parse(typeof(Wqn.Administration.UI.FraudService.Website),cmbWebsite.SelectedItem.ToString()); //for binding the second observablecollection******* manageFraudOrderViewModel.LoadOrders(website); this.DataContext = manageFraudOrderViewModel; //for binding the second observablecollection******* } } } #endregion } XAML ComboBox x:Name="cmbWebsite" ItemsSource="{Binding Sites}" Margin="5" Width="100" Height="25" SelectionChanged="cmbWebsite_SelectionChanged" DataGrid ItemsSource ={Binding Path = LoadFraudResults} PROBLEM AREA: When I call the LoadOrderQueueForm to bind the first observablecollection and later BindItemsSource to bind 2ed observable collection, everything works fine and no problem for the first time binding. But, when I call BindItemsSource again to repopulate the obseravablecollection based on changed selected combo value via cmbWebsite_SelectionChanged, the observalblecollection gets populated with new value and LoadFraudResults property in viewmodule is populated with new values; but when i call the datacontext to rebind the datagrid,the datagrid does not reflect the changed values. In other words the datagrid doesnot get changed when the datacontext is called the 2ed time in BindItemsSource method of the view. manageFraudOrderViewModel.LoadOrders(website); this.DataContext = manageFraudOrderViewModel; manageFraudOrderViewModel values are correct but the datagrid is not relected with changed values. Please help as I am stuck with this thing for past 2 days and the deadline is approaching near. Thanks in advance

    Read the article

  • How to best propagate changes upwards a hierarchical structure for binding?

    - by H.B.
    If i have a folder-like structure that uses the composite design pattern and i bind the root folder to a TreeView. It would be quite useful if i can display certain properties that are being accumulated from the folder's contents. The question is, how do i best inform the folder that changes occurred in a child-element so that the accumulative properties get updated? The context in which i need this is a small RSS-FeedReader i am trying to make. This are the most important objects and aspects of my model: Composite interface: public interface IFeedComposite : INotifyPropertyChanged { string Title { get; set; } int UnreadFeedItemsCount { get; } ObservableCollection<FeedItem> FeedItems { get; } } FeedComposite (aka Folder) public class FeedComposite : BindableObject, IFeedComposite { private string title = ""; public string Title { get { return title; } set { title = value; NotifyPropertyChanged("Title"); } } private ObservableCollection<IFeedComposite> children = new ObservableCollection<IFeedComposite>(); public ObservableCollection<IFeedComposite> Children { get { return children; } set { children.Clear(); foreach (IFeedComposite item in value) { children.Add(item); } NotifyPropertyChanged("Children"); } } public FeedComposite() { } public FeedComposite(string title) { Title = title; } public ObservableCollection<FeedItem> FeedItems { get { ObservableCollection<FeedItem> feedItems = new ObservableCollection<FeedItem>(); foreach (IFeedComposite child in Children) { foreach (FeedItem item in child.FeedItems) { feedItems.Add(item); } } return feedItems; } } public int UnreadFeedItemsCount { get { return (from i in FeedItems where i.IsUnread select i).Count(); } } Feed: public class Feed : BindableObject, IFeedComposite { private string url = ""; public string Url { get { return url; } set { url = value; NotifyPropertyChanged("Url"); } } ... private ObservableCollection<FeedItem> feedItems = new ObservableCollection<FeedItem>(); public ObservableCollection<FeedItem> FeedItems { get { return feedItems; } set { feedItems.Clear(); foreach (FeedItem item in value) { AddFeedItem(item); } NotifyPropertyChanged("Items"); } } public int UnreadFeedItemsCount { get { return (from i in FeedItems where i.IsUnread select i).Count(); } } public Feed() { } public Feed(string url) { Url = url; } Ok, so here's the thing, if i bind a TextBlock.Text to the UnreadFeedItemsCount there won't be simple notifications when an item is marked unread, so one of my approaches has been to handle the PropertyChanged event of every FeedItem and if the IsUnread-Property is changed i have my Feed make a notification that the property UnreadFeedItemsCount has been changed. With this approach i also need to handle all PropertyChanged events of all Feeds and FeedComposites in Children of FeedComposite, from the sound of it, it should be obvious that this is not such a very good idea, you need to be very careful that items never get added or removed to any collection without having attached the PropertyChanged event handler first and things like that. Also: What do i do with the CollectionChanged-Events which necessarily also cause a change in the sum of the unread items count? Sounds like more event handling fun. It is such a mess, it would be great if anyone has an elegant solution to this since i don't want the feed-reader to end up as awful as my first attempt years ago when i didn't even know about DataBinding...

    Read the article

  • DataContractSerializer: type is not serializable because it is not public?

    - by Michael B. McLaughlin
    I recently ran into an odd and annoying error when working with the DataContractSerializer class for a WP7 project. I thought I’d share it to save others who might encounter it the same annoyance I had. So I had an instance of  ObservableCollection<T> that I was trying to serialize (with T being a class I wrote for the project) and whenever it would hit the code to save it, it would give me: The data contract type 'ProjectName.MyMagicItemsClass' is not serializable because it is not public. Making the type public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications. This, of course, was malarkey. I was trying to write an instance of MyAwesomeClass that looked like this: [DataContract] public class MyAwesomeClass { [DataMember] public ObservableCollection<MyMagicItemsClass> GreatItems { get; set; }   [DataMember] public ObservableCollection<MyMagicItemsClass> SuperbItems { get; set; }     public MyAwesomeClass { GreatItems = new ObservableCollection<MyMagicItemsClass>(); SuperbItems = new ObservableCollection<MyMagicItemsClass>(); } }   That’s all well and fine. And MyMagicItemsClass was also public with a parameterless public constructor. It too had DataContractAttribute applied to it and it had DataMemberAttribute applied to all the properties and fields I wanted to serialize. Everything should be cool, but it’s not because I keep getting that “not public” exception. I could tell you about all the things I tried (generating a List<T> on the fly to make sure it wasn’t ObservableCollection<T>, trying to serialize the the Collections directly, moving it all to a separate library project, etc.), but I want to keep this short. In the end, I remembered my the “Debug->Exceptions…” VS menu option that brings up the list of exception-related circumstances under which the Visual Studio debugger will break. I checked the “Thrown” checkbox for “Common Language Runtime Exceptions”, started the project under the debugger, and voilà: the true problem revealed itself. Some of my properties had fairly elaborate setters whose logic I wanted to ignore. So for some of them, I applied an IgnoreDataMember attribute to them and applied the DataMember attribute to the underlying fields instead. All of which, in line with good programming practices, were private. Well, it just so happens that WP7 apps run in a “partial trust” environment and outside of “full trust”-land, DataContractSerializer refuses to serialize or deserialize non-public members. Of course that exception was swallowed up internally by .NET so all I ever saw was that bizarre message about things that I knew for certain were public being “not public”. I changed all the private fields I was serializing to public and everything worked just fine. In hindsight it all makes perfect sense. The serializer uses reflection to build up its graph of the object in order to write it out. In partial trust, you don’t want people using reflection to get at non-public members of an object since there are potential security problems with allowing that (you could break out of the sandbox pretty quickly by reflecting and calling the appropriate methods and cause some havoc by reflecting and setting the appropriate fields in certain circumstances. The fact that you cannot reflect your own assembly seems a bit heavy-handed, but then again I’m not a compiler writer or a framework designer and I have no idea what sorts of difficulties would go into allowing that from a compilation standpoint or what sorts of security problems allowing that could present (if any). So, lesson learned. If you get an incomprehensible exception message, turn on break on all thrown exceptions and try running it again (it might take a couple of tries, depending) and see what pops out. Chances are you’ll find the buried exception that actually explains what was going on. And if you’re getting a weird exception when trying to use DataContractSerializer complaining about public types not being public, chances are you’re trying to serialize a private or protected field/property.

    Read the article

  • Custom WPF TreeView

    - by Robert
    I have a custom class that I would like to bind a WPF TreeView that has three tiers. Each tier needs to be bound like this: Monitor --> LCD --> Samsung 1445 LCD --> CRT --> Sony 125 CRT Here is the example code: public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); SystemInventory sysInventory = new SystemInventory(); //Possibly do something like this. _myTreeView.DataContext = sysInventory.DeviceGroupInstances; } public class SystemInventory { public ObservableCollection<DeviceGroup> DeviceGroupInstances { get; set; } public SystemInventory() { DeviceGroupInstances = new ObservableCollection<DeviceGroup>(); DeviceGroupInstances.Add(new DeviceGroup("Monitor")); } } public class DeviceGroup { public string DeviceGroupName { get; set; } public ObservableCollection<DeviceType> DeviceTypeInstances { get; set; } public DeviceGroup(string deviceGroupName) { DeviceTypeInstances = new ObservableCollection<DeviceType>(); DeviceGroupName = deviceGroupName; if (deviceGroupName == "Monitor") { DeviceTypeInstances.Add(new DeviceType("LCD")); DeviceTypeInstances.Add(new DeviceType("CRT")); } } } public class DeviceType { public string DeviceTypeName { get; set; } public ObservableCollection<DeviceInstance> DeviceInstances { get; set; } public DeviceType(string deviceGroupName) { DeviceInstances = new ObservableCollection<DeviceInstance>(); DeviceTypeName = deviceGroupName; if (deviceGroupName == "Monitor") { DeviceInstances.Add(new DeviceInstance("Samsung 1445 LCD")); } else { DeviceInstances.Add(new DeviceInstance("Sony 125 CRT")); } } } public class DeviceInstance { public string DeviceInstanceName { get; set; } public DeviceInstance(string instanceName) { DeviceInstanceName = instanceName; } } }

    Read the article

  • Should Item Grouping/Filter be in the ViewModel or View layer?

    - by ronag
    I'm in a situation where I have a list of items that need to be displayed depending on their properties. What I'm unsure of is where is the best place to put the filtering/grouping logic of the viewmodel state? Currently I have it in my view using converters, but I'm unsure whether I should have the logic in the viewmodel? e.g. ViewModel Layer: class ItemViewModel { DateTime LastAccessed { get; set; } bool IsActive { get; set; } } class ContainerViewModel { ObservableCollection<Item> Items {get; set;} } View Layer: <TextView Text="Active Items"/> <List ItemsSource={Binding Items, Converter=GroupActiveItemsByDay}/> <TextView Text="Active Items"/> <List ItemsSource={Binding Items, Converter=GroupInActiveItemsByDay}/> or should I build it like this? ViewModel Layer: class ContainerViewModel { ObservableCollection<IGrouping<string, Item>> ActiveItemsByGroup {get; set;} ObservableCollection<IGrouping<string, Item>> InActiveItemsByGroup {get; set;} } View Layer: <TextView Text="Active Items"/> <List ItemsSource={Binding ActiveItemsGroupByDate }/> <TextView Text="Active Items"/> <List ItemsSource={Binding InActiveItemsGroupByDate }/> Or maybe something in between? ViewModel Layer: class ContainerViewModel { ObservableCollection<IGrouping<string, Item>> ActiveItems {get; set;} ObservableCollection<IGrouping<string, Item>> InActiveItems {get; set;} } View Layer: <TextView Text="Active Items"/> <List ItemsSource={Binding ActiveItems, Converter=GroupByDate }/> <TextView Text="Active Items"/> <List ItemsSource={Binding InActiveItems, Converter=GroupByDate }/> I guess my question is what is good practice in terms as to what logic to put into the ViewModel and what logic to put into the Binding in the View, as they seem to overlap a bit?

    Read the article

  • WPF: Problem with TreeView databinding

    - by Am
    Hi, I have a tree view defined as follows: <TreeView Grid.Row="0" Grid.Column="0" Margin="0" FlowDirection="LeftToRight" ItemTemplate="{StaticResource NavigationHeaderTemplate}" Name="TreeView2"> </TreeView> The data binding is: public class ViewTag : INotifyPropertyChanged { private string _tagName; public string TagName { get { return _tagName; } set { _tagName = value; PropertyChanged(this, new PropertyChangedEventArgs("Tag Name")); } } private ObservableCollection<ViewTag> _childTags; public ObservableCollection<ViewTag> ChildTags { get { return _childTags; } set { _childTags = value; OnPropertyChanged(new PropertyChangedEventArgs("Child Tags")); } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(PropertyChangedEventArgs e) { if (PropertyChanged != null) PropertyChanged(this, e); } #endregion public ViewTag(string tagName, ObservableCollection<ViewTag> childTags) { _tagName = tagName; _childTags = childTags; } } And my test binding is: List<ViewTag> tempTags = new List<ViewTag>(); ViewTag t1, t2, t3, t4, t5, t6; t1 = new ViewTag("Computers", null); t2 = new ViewTag("Chemistry", null); t3 = new ViewTag("Physics", null); var t123 = new ObservableCollection<ViewTag>(); t123.Add(t1); t123.Add(t2); t123.Add(t3); t4 = new ViewTag("Science", t123); var t1234 = new ObservableCollection<ViewTag>(); t1234.Add(t4); t5 = new ViewTag("All Items", t1234); t6 = new ViewTag("Untagged", null); var tall = new ObservableCollection<ViewTag>(); tall.Add(t5); tall.Add(t6); xy.Add(new ViewNavigationTree() { Header = "Tags", Image = "img/tags2.ico", Children = tall }); var rootFolders = eDataAccessLayer.RepositoryFacrory.Instance.MonitoredDirectoriesRepository.Directories.ToList(); var viewFolders = new ObservableCollection<ViewTag>(); foreach (var vf in rootFolders) { viewFolders.Add(new ViewTag(vf.FullPath, null)); } xy.Add(new ViewNavigationTree() { Header = "Folders", Image = "img/folder_16x16.png", Children = viewFolders }); xy.Add(new ViewNavigationTree() { Header = "Authors", Image = "img/user_16x16.png", Children = null }); xy.Add(new ViewNavigationTree() { Header = "Publishers", Image = "img/powerplant_32.png", Children = null }); TreeView2.ItemsSource = xy; Problem is, the tree only shows: + Tags All Items Untagged + Folders dir 1 dir 2 ... Authors Publishers The items I added under "All Items" aren't displayed. Being a WPF nub, i can't put my finger on the problem. Any help will be greatly appriciated.

    Read the article

  • RIA Services EntitySet does not support 'Edit' opperation

    - by Savvas Sopiadis
    Hello everbody! Making my first steps in RIA Services (VS2010Beta2) and i encountered this problem: created an EF Model (no POCOs), generic repository on top of it and a RIA Service(hosted in an ASP.NET MVC application) and tryed to get data from within the ASP.NET MVC application: worked well. Next step: Silverlight client. Got a reference to the RIAService (through its context), queried for all the records of the repository and got them into the SL application as well (using this code sample): private ObservableCollection<Culture> _cultures = new ObservableCollection<Culture>(); public ObservableCollection<Culture> cultures { get { return _cultures; } set { _cultures = value; RaisePropertyChanged("cultures"); } } .... //Get cultures EntityQuery<Culture> queryCultures = from cu in dsCtxt.GetAllCulturesQuery() select cu; loCultures = dsCtxt.Load(queryCultures); loCultures.Completed += new EventHandler(lo_Completed); .... void loAnyCulture_Completed(object sender, EventArgs e) { ObservableCollection<Culture> temp= new ObservableCollection<Culture>loAnyCulture.Entities); AnyCulture = temp[0]; } The problem is this: whenever i try to edit some data of a record (in this example the first record) i get this error: This EntitySet of type 'Culture' does not support the 'Edit' operation. I thought that i did something weird and tryed to create an object of type Culture and assign a value to it: it worked well! What am i missing? Do i have to declare an EntitySet? Do i have to mark it? Do i have to...what? Thanks in advance

    Read the article

  • Wpf Combobox in Master/Detail MVVM

    - by isak
    I have MVVM master /details like this: <Window.Resources> <DataTemplate DataType="{x:Type model:EveryDay}"> <views:EveryDayView/> </DataTemplate> <DataTemplate DataType="{x:Type model:EveryMonth}"> <views:EveryMonthView/> </DataTemplate> </Window.Resources> <Grid> <ListBox Margin="12,24,0,35" Name="schedules" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Path=Elements}" SelectedItem="{Binding Path=CurrentElement}" DisplayMemberPath="Name" HorizontalAlignment="Left" Width="120"/> <ContentControl Margin="168,86,32,35" Name="contentControl1" Content="{Binding Path=CurrentElement.Schedule}" /> <ComboBox Height="23" Margin="188,24,51,0" Name="comboBox1" VerticalAlignment="Top" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Path=Schedules}" SelectedItem="{Binding Path=CurrentElement.Schedule}" DisplayMemberPath="Name" SelectedValuePath="ID" SelectedValue="{Binding Path=CurrentElement.Schedule.ID}" /> </Grid> This Window has DataContext class: public class MainViewModel : INotifyPropertyChanged { public MainViewModel() { _elements.Add(new Element("first", new EveryDay("First EveryDay object"))); _elements.Add(new Element("second", new EveryMonth("Every Month object"))); _elements.Add(new Element("third", new EveryDay("Second EveryDay object"))); _schedules.Add(new EveryDay()); _schedules.Add(new EveryMonth()); } private ObservableCollection<ScheduleBase> _schedules = new ObservableCollection<ScheduleBase>(); public ObservableCollection<ScheduleBase> Schedules { get { return _schedules; } set { _schedules = value; this.OnPropertyChanged("Schedules"); } } private Element _currentElement = null; public Element CurrentElement { get { return this._currentElement; } set { this._currentElement = value; this.OnPropertyChanged("CurrentElement"); } } private ObservableCollection<Element> _elements = new ObservableCollection<Element>(); public ObservableCollection<Element> Elements { get { return _elements; } set { _elements = value; this.OnPropertyChanged("Elements"); } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } #endregion } One of Views: <UserControl x:Class="Views.EveryDayView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" > <Grid > <GroupBox Header="Every Day Data" Name="groupBox1" VerticalAlignment="Top"> <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <TextBox Name="textBox2" Text="{Binding Path=AnyDayData}" /> </Grid> </GroupBox> </Grid> I have problem with SelectedItem in ComboBox.It doesn't works correctly.

    Read the article

  • Generic method to create deep copy of all elements in a collection

    - by bwarner
    I have various ObservableCollections of different object types. I'd like to write a single method that will take a collection of any of these object types and return a new collection where each element is a deep copy of elements in the given collection. Here is an example for a specifc class private static ObservableCollection<PropertyValueRow> DeepCopy(ObservableCollection<PropertyValueRow> list) { ObservableCollection<PropertyValueRow> newList = new ObservableCollection<PropertyValueRow>(); foreach (PropertyValueRow rec in list) { newList.Add((PropertyValueRow)rec.Clone()); } return newList; } How can I make this method generic for any class which implements ICloneable?

    Read the article

  • How can I add headers to DualList control wpf

    - by devnet247
    Hi all I am trying to write a Dual List usercontrol in wpf. I am new to wpf and I am finding it quite difficult. This is something I have put together in a couple of hours.It's not that good but a start. I would be extremely grateful if somebody with wpf experience could improve it. The aim is to simplify the usage as much as possible I am kind of stuck. I would like the user of the DualList Control to be able to set up headers how do you do that. Do I need to expose some dependency properties in my control? At the moment when loading the user has to pass a ObservableCollection is there a better way? Could you have a look and possibly make any suggestions with some code? Thanks a lot!!!!! xaml <Grid ShowGridLines="False"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="25px"></ColumnDefinition> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="*"></RowDefinition> </Grid.RowDefinitions> <StackPanel Orientation="Vertical" Grid.Column="0" Grid.Row="0"> <Label Name="lblLeftTitle" Content="Available"></Label> <ListView Name="lvwLeft"> </ListView> </StackPanel> <WrapPanel Grid.Column="1" Grid.Row="0"> <Button Name="btnMoveRight" Content=">" Width="25" Margin="0,35,0,0" Click="btnMoveRight_Click" /> <Button Name="btnMoveAllRight" Content=">>" Width="25" Margin="0,05,0,0" Click="btnMoveAllRight_Click" /> <Button Name="btnMoveLeft" Content="&lt;" Width="25" Margin="0,25,0,0" Click="btnMoveLeft_Click" /> <Button Name="btnMoveAllLeft" Content="&lt;&lt;" Width="25" Margin="0,05,0,0" Click="btnMoveAllLeft_Click" /> </WrapPanel> <StackPanel Orientation="Vertical" Grid.Column="2" Grid.Row="0"> <Label Name="lblRightTitle" Content="Selected"></Label> <ListView Name="lvwRight"> </ListView> </StackPanel> </Grid> Client public partial class DualListTest { public ObservableCollection<ListViewItem> LeftList { get; set; } public ObservableCollection<ListViewItem> RightList { get; set; } public DualListTest() { InitializeComponent(); LoadCustomers(); LoadDualList(); } private void LoadDualList() { dualList1.Load(LeftList, RightList); } private void LoadCustomers() { //Pretend we are getting a list of Customers from a repository. //Some go in the left List(Good Customers) some go in the Right List(Bad Customers). LeftList = new ObservableCollection<ListViewItem>(); RightList = new ObservableCollection<ListViewItem>(); var customers = GetCustomers(); foreach (var customer in customers) { if (customer.Status == CustomerStatus.Good) { LeftList.Add(new ListViewItem { Content = customer }); } else { RightList.Add(new ListViewItem{Content=customer }); } } } private static IEnumerable<Customer> GetCustomers() { return new List<Customer> { new Customer {Name = "Jo Blogg", Status = CustomerStatus.Good}, new Customer {Name = "Rob Smith", Status = CustomerStatus.Good}, new Customer {Name = "Michel Platini", Status = CustomerStatus.Good}, new Customer {Name = "Roberto Baggio", Status = CustomerStatus.Good}, new Customer {Name = "Gio Surname", Status = CustomerStatus.Bad}, new Customer {Name = "Diego Maradona", Status = CustomerStatus.Bad} }; } } UserControl public partial class DualList:UserControl { public ObservableCollection<ListViewItem> LeftListCollection { get; set; } public ObservableCollection<ListViewItem> RightListCollection { get; set; } public DualList() { InitializeComponent(); } public void Load(ObservableCollection<ListViewItem> leftListCollection, ObservableCollection<ListViewItem> rightListCollection) { LeftListCollection = leftListCollection; RightListCollection = rightListCollection; lvwLeft.ItemsSource = leftListCollection; lvwRight.ItemsSource = rightListCollection; EnableButtons(); } public static DependencyProperty LeftTitleProperty = DependencyProperty.Register("LeftTitle", typeof(string), typeof(Label)); public static DependencyProperty RightTitleProperty = DependencyProperty.Register("RightTitle", typeof(string), typeof(Label)); public static DependencyProperty LeftListProperty = DependencyProperty.Register("LeftList", typeof(ListView), typeof(DualList)); public static DependencyProperty RightListProperty = DependencyProperty.Register("RightList", typeof(ListView), typeof(DualList)); public string LeftTitle { get { return (string)lblLeftTitle.Content; } set { lblLeftTitle.Content = value; } } public string RightTitle { get { return (string)lblRightTitle.Content; } set { lblRightTitle.Content = value; } } public ListView LeftList { get { return lvwLeft; } set { lvwLeft = value; } } public ListView RightList { get { return lvwRight; } set { lvwRight = value; } } private void EnableButtons() { if (lvwLeft.Items.Count > 0) { btnMoveRight.IsEnabled = true; btnMoveAllRight.IsEnabled = true; } else { btnMoveRight.IsEnabled = false; btnMoveAllRight.IsEnabled = false; } if (lvwRight.Items.Count > 0) { btnMoveLeft.IsEnabled = true; btnMoveAllLeft.IsEnabled = true; } else { btnMoveLeft.IsEnabled = false; btnMoveAllLeft.IsEnabled = false; } if (lvwLeft.Items.Count != 0 || lvwRight.Items.Count != 0) return; btnMoveLeft.IsEnabled = false; btnMoveAllLeft.IsEnabled = false; btnMoveRight.IsEnabled = false; btnMoveAllRight.IsEnabled = false; } private void MoveRight() { while (lvwLeft.SelectedItems.Count > 0) { var selectedItem = (ListViewItem)lvwLeft.SelectedItem; LeftListCollection.Remove(selectedItem); RightListCollection.Add(selectedItem); } lvwRight.ItemsSource = RightListCollection; lvwLeft.ItemsSource = LeftListCollection; EnableButtons(); } private void MoveAllRight() { while (lvwLeft.Items.Count > 0) { var item = (ListViewItem)lvwLeft.Items[lvwLeft.Items.Count - 1]; LeftListCollection.Remove(item); RightListCollection.Add(item); } lvwRight.ItemsSource = RightListCollection; lvwLeft.ItemsSource = LeftListCollection; EnableButtons(); } private void MoveAllLeft() { while (lvwRight.Items.Count > 0) { var item = (ListViewItem)lvwRight.Items[lvwRight.Items.Count - 1]; RightListCollection.Remove(item); LeftListCollection.Add(item); } lvwRight.ItemsSource = RightListCollection; lvwLeft.ItemsSource = LeftListCollection; EnableButtons(); } private void MoveLeft() { while (lvwRight.SelectedItems.Count > 0) { var selectedCustomer = (ListViewItem)lvwRight.SelectedItem; LeftListCollection.Add(selectedCustomer); RightListCollection.Remove(selectedCustomer); } lvwRight.ItemsSource = RightListCollection; lvwLeft.ItemsSource = LeftListCollection; EnableButtons(); } private void btnMoveLeft_Click(object sender, RoutedEventArgs e) { MoveLeft(); } private void btnMoveAllLeft_Click(object sender, RoutedEventArgs e) { MoveAllLeft(); } private void btnMoveRight_Click(object sender, RoutedEventArgs e) { MoveRight(); } private void btnMoveAllRight_Click(object sender, RoutedEventArgs e) { MoveAllRight(); } }

    Read the article

  • Pass Data to Data Template Selector

    - by Michael Sync
    How do you guys pass the data (parameter) to DataTemplate Selector? The only one that I can think of is to use an attached property in DataTemplate Selector? Example: public class DisableWeekendsSelection : DataTemplateSelector { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible", Justification = "DependencyProperty")] public static readonly DependencyProperty Parameter = DependencyProperty.RegisterAttached("Parameter", typeof(ObservableCollection<Date>), typeof(DisableWeekendsSelection), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); public static ObservableCollection<Date> GetParameter(DependencyObject dp) { return dp.GetValue(Parameter) as ObservableCollection<Date>; } public static void SetParameter(DependencyObject dp, ObservableCollection<Date> value) { dp.SetValue(Parameter, value); } public override DataTemplate SelectTemplate(object item, DependencyObject container) { The problem with this approach is that I'm not able to get the value of Parameter in SelectTemplate method. Any suggestion would be appreciated. Thanks in advance.

    Read the article

  • Master Details and collectionViewSource in separate views cannot make it work.

    - by devnet247
    Hi all, I really cannot seem to make/understand how it works with separate views It all works fine if a bundle all together in a single window. I have a list of Countries-Cities-etc... When you select a country it should load it's cities. Works So I bind 3 listboxes successfully using collection sources and no codebehind more or less (just code to set the datacontext and selectionChanged). you can download the project here http://cid-9db5ae91a2948485.skydrive.live.com/self.aspx/PublicFolder/2MasterDetails.zip <Window.Resources> <CollectionViewSource Source="{Binding}" x:Key="cvsCountryList"/> <CollectionViewSource Source="{Binding Source={StaticResource cvsCountryList},Path=Cities}" x:Key="cvsCityList"/> <CollectionViewSource Source="{Binding Source={StaticResource cvsCityList},Path=Hotels}" x:Key="cvsHotelList"/> </Window.Resources> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition/> </Grid.RowDefinitions> <TextBlock Grid.Column="0" Grid.Row="0" Text="Countries"/> <TextBlock Grid.Column="1" Grid.Row="0" Text="Cities"/> <TextBlock Grid.Column="2" Grid.Row="0" Text="Hotels"/> <ListBox Grid.Column="0" Grid.Row="1" Name="lstCountries" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Source={StaticResource cvsCountryList}}" DisplayMemberPath="Name" SelectionChanged="OnSelectionChanged"/> <ListBox Grid.Column="1" Grid.Row="1" Name="lstCities" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Source={StaticResource cvsCityList}}" DisplayMemberPath="Name" SelectionChanged="OnSelectionChanged"/> <ListBox Grid.Column="2" Grid.Row="1" Name="lstHotels" ItemsSource="{Binding Source={StaticResource cvsHotelList}}" DisplayMemberPath="Name" SelectionChanged="OnSelectionChanged"/> </Grid> Does not work I am trying to implement the same using a view for each eg(LeftSideMasterControl -RightSideDetailsControls) However I cannot seem to make them bind. Can you help? I would be very grateful so that I can understand how you communicate between userControls You can download the project here. http://cid-9db5ae91a2948485.skydrive.live.com/self.aspx/PublicFolder/2MasterDetails.zip I have as follows LeftSideMasterControl.xaml <Grid> <ListBox Name="lstCountries" SelectionChanged="OnSelectionChanged" DisplayMemberPath="Name" ItemsSource="{Binding Countries}"/> </Grid> RightViewDetailsControl.xaml MainView.xaml <CollectionViewSource Source="{Binding}" x:Key="cvsCountryList"/> <CollectionViewSource Source="{Binding Source={StaticResource cvsCountryList},Path=Cities}" x:Key="cvsCityList"/> </UserControl.Resources> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition Width="3*"/> </Grid.ColumnDefinitions> <Views:LeftViewMasterControl x:Name="leftSide" Margin="5" Content="{Binding Source=}"/> <GridSplitter Grid.Column="0" Grid.Row="0" Background="LightGray"/> <Views:RightViewDetailsControl Grid.Column="1" x:Name="RightSide" Margin="5"/> </Grid> ViewModels public class CountryListVM : ViewModelBase { public CountryListVM() { Countries = new ObservableCollection<CountryVM>(); } public ObservableCollection<CountryVM> Countries { get; set; } private RelayCommand _loadCountriesCommand; public ICommand LoadCountriesCommand { get { return _loadCountriesCommand ?? (_loadCountriesCommand = new RelayCommand(x => LoadCountries(), x => CanLoadCountries)); } } private static bool CanLoadCountries { get { return true; } } private void LoadCountries() { var countryList = Repository.GetCountries(); foreach (var country in countryList) { Countries.Add(new CountryVM { Name = country.Name }); } } } public class CountryVM : ViewModelBase { private string _name; public string Name { get { return _name; } set { _name = value; OnPropertyChanged("Name"); } } } public class CityListVM : ViewModelBase { private CountryVM _selectedCountry; public CityListVM(CountryVM country) { SelectedCountry = country; Cities = new ObservableCollection<CityVM>(); } public ObservableCollection<CityVM> Cities { get; set; } public CountryVM SelectedCountry { get { return _selectedCountry; } set { _selectedCountry = value; OnPropertyChanged("SelectedCountry"); } } private RelayCommand _loadCitiesCommand; public ICommand LoadCitiesCommand { get { return _loadCitiesCommand ?? (_loadCitiesCommand = new RelayCommand(x => LoadCities(), x => CanLoadCities)); } } private static bool CanLoadCities { get { return true; } } private void LoadCities() { var cities = Repository.GetCities(SelectedCountry.Name); foreach (var city in cities) { Cities.Add(new CityVM() { Name = city.Name }); } } } public class CityVM : ViewModelBase { private string _name; public string Name { get { return _name; } set { _name = value; OnPropertyChanged("Name"); } } } Models ========= public class Country { public Country() { Cities = new ObservableCollection<City>(); } public string Name { get; set; } public ObservableCollection<City> Cities { get; set; } } public class City { public City() { Hotels = new ObservableCollection<Hotel>(); } public string Name { get; set; } public ObservableCollection<Hotel> Hotels { get; set; } } public class Hotel { public string Name { get; set; } }

    Read the article

  • How to set focus to a brand new TextBox which was created as a result of a databinding in WPF?

    - by Mike
    Hi everyone, I have a WPF ItemsControl that is bound to an ObservableCollection. The XAML: <ItemsControl Name="mItemsControl"> <ItemsControl.ItemTemplate> <DataTemplate> <TextBox Text="{Binding Mode=OneWay}"></TextBox> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> The codebehind: private ObservableCollection<string> mCollection = new ObservableCollection<string>(); public MainWindow() { InitializeComponent(); this.mCollection.Add("Test1"); this.mCollection.Add("Test2"); this.mItemsControl.ItemsSource = this.mCollection; } private void Button_Click(object sender, RoutedEventArgs e) { this.mCollection.Add("new item!"); } When I click a button, it adds a new string to the databound ObservableCollection which triggers a new TextBox to appear. I want to give this new textbox focus. I've tried this technique from a related StackOverflow question but it always sets focus to the textbox before the newly created one. private void Button_Click(object sender, RoutedEventArgs e) { this.mCollection.Add("new item!"); // MoveFocus takes a TraversalRequest as its argument. TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Previous); // Gets the element with keyboard focus. UIElement elementWithFocus = Keyboard.FocusedElement as UIElement; // Change keyboard focus. if (elementWithFocus != null) { elementWithFocus.MoveFocus(request); } } My need seems simple enough, but it's almost like the new textbox doesn't really exist until a slight delay after something is added to the ObservableCollection. Any ideas of what would work? Thanks! -Mike

    Read the article

  • Silverlight 4 Datagrid Sorting

    - by DavyMac23
    I'm having a heck of a time trying to get a silverlight datagrid to properly sort, and do so quickly (sub 1/10 second). Here's the scenario: -WCF callback every 1/5 of a second -Take the callback, match up to the existing record in an ObservableCollection -Update the ObservableCollection's properties -Bind the grid. I've tried a linq query, PagedCollectionView, and observablecollection.select(), all are waaaaaaay too slow, and introduce 12+ second delays in processing. Anyone else experience this?

    Read the article

  • Failing to add different items in combobox on dynamic radiobutton click

    - by Steven Wilson
    I am working on radiobuttons and combobox in my wpf App. Although I am a C++ developer, I recently moved to C#. My app deals with dynamic generation of the above mentioned components. Basically I have created 4 dynamic radiobuttons in my app and on clicking each, i should should add different items to my combobox. Here is the code: XAML: <ItemsControl ItemsSource="{Binding Children}"> <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel Orientation="Vertical" > <RadioButton Content="{Binding RadioBase}" Margin="0,10,0,0" IsChecked="{Binding BaseCheck}" GroupName="SlotGroup" Height="15" Width="80" HorizontalAlignment="Center" VerticalAlignment="Center"/> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> <ComboBox Visibility="{Binding IsRegisterItemsVisible}" ItemsSource="{Binding RegComboList}" SelectedItem="{Binding SelectedRegComboList, Mode=TwoWay}" SelectedIndex="0" /> FPGARadioWidgetViewModel Class: public ObservableCollection<FPGAViewModel> Children { get; set; } public FPGARadioWidgetViewModel() { Children = new ObservableCollection<FPGAViewModel>(); Children.Add(new FPGAViewModel() { RadioBase = "Base 0x0", ID = 0 }); Children.Add(new FPGAViewModel() { RadioBase = "Base 0x40", ID = 1 }); Children.Add(new FPGAViewModel() { RadioBase = "Base 0x80", ID = 2 }); Children.Add(new FPGAViewModel() { RadioBase = "Base 0xc0", ID = 3 }); } FPGAViewModel Class: private bool sBaseCheck; public bool BaseCheck { get { return this.sBaseCheck; } set { this.sBaseCheck = value; AddComboItems(); this.OnPropertyChanged("BaseCheck"); } } private ObservableCollection<string> _RegComboList; public ObservableCollection<string> RegComboList { get { return _RegComboList; } set { _RegComboList = value; OnPropertyChanged("RegComboList"); } } private void AddComboItems() { int baseRegister = 0x40 * ID; ObservableCollection<string> combo = new ObservableCollection<string>(); for (int i = 0; i < 0x40; i++) { int reg = (i * 8) + baseRegister; combo[i] = "0x" + reg.ToString("X"); } RegComboList = new ObservableCollection<String>(combo); OnPropertyChanged("RegComboList"); } private bool isRegisterItemsVisible = false; public bool IsRegisterItemsVisible { get { return isRegisterItemsVisible; } set { isRegisterItemsVisible = value; OnPropertyChanged("IsRegisterItemsVisible"); OnPropertyChanged("RegComboList"); } } If you notice, on clicking a particular radiobutton, it should add items with different value in combobox based on ID. It has to be made sure that on clicking any radiobutton only the items of that should be added and previous content of combobox should be cleared. I am trying to do the same thing using my above code but nothing seems to appear in combobox when i debug. Please help :)

    Read the article

  • Disable Adding Item to Collection

    - by Wonko the Sane
    Hi All, I'm sure there's an "easy" answer to this, but for the moment it escapes me. In an MVVM application, I have a property that is a ObservableCollection, used for displaying some set of elements on the view. private readonly ObservableCollection<MyType> mMyCollection = new ObservableCollection<MyType>(); public ObservableCollection<MyType> MyCollection { get { return mMyCollection; } } I want to restrict consumers of this collection from simply using the property to add to the collection (i.e. I want to prevent this from the view): viewModel.MyCollection.Add(newThing); // want to prevent this! Instead, I want to force the use of a method to add items, because there may be another thread using that collection, and I don't want to modify the collection while that thread is processing it. public void AddToMyCollection(MyType newItem) { // Do some thread/task stuff here } Thanks, wTs

    Read the article

  • Rendering My Fault Message

    - by onefloridacoder
    My coworkers setup  a nice way to get the fault messages from our service layer all the way back to the client’s service proxy layer.  This is what I needed to work on this afternoon.  Through a series of trials and errors I finally figured this out. The confusion was how I was looking at the exception in the quick watch viewer.  It appeared as though the EventArgs from the service call had somehow magically been cast back to FaultException(), not FaultException<T>.  I drilled into the EventArgs object with the quick watch and I copied this code to figure out where the Fault message was hiding.  Further, when I copied this quick watch code into the IDE I got squigglies.  Poop. 1: ((System 2: .ServiceModel 3: .FaultException<UnhandledExceptionFault>)(((System.Exception)(e.Result)).InnerException)).Detail.FaultMessage I wont bore you with the details but here’s how it turned out.   EventArgs which I’m calling “e” is not the result such as some collection of items you’re expecting.  It’s actually a FaultException, or in my case FaultException<T>.  Below is the calling code and the callback to handle the expected response or the fault from the completed event. 1: public void BeginRetrieveItems(Action<ObservableCollection<Model.Widget>> FindItemsCompleteCallback, Model.WidgetLocation location) 2: { 3: var proxy = new MyServiceContractClient(); 4:  5: proxy.RetrieveWidgetsCompleted += (s, e) => FindWidgetsCompleteCallback(FindWidgetsCompleted(e)); 6:  7: RetrieveWidgetsRequest request = new RetrieveWidgetsRequest { location.Id }; 8:  9: proxy.RetrieveWidgetsAsync(request); 10: } 11:  12: private ObservableCollection<Model.Widget> FindItemsCompleted(RetrieveWidgetsCompletedEventArgs e) 13: { 14: if (e.Error is FaultException<UnhandledExceptionFault>) 15: { 16: var fault = (FaultException<UnhandledExceptionFault>)e.Error; 17: var faultDetailMessage = fault.Detail.FaultMessage; 18:  19: UIMessageControlDuJour.Show(faultDetailMessage); 20: return new ObservableCollection<BinInventoryItemCountInfo>(); 21: } 22:  23: var widgets = new ObservableCollection<Model.Widget>(); 24:  25: if (e.Result.Widgets != null) 26: { 27: e.Result.Widgets.ToList().ForEach(w => widgets.Add(this.WidgetMapper.Map(w))); 28: } 29:  30: return widgets; 31: }

    Read the article

  • Silverlight Recruiting Application Part 5 - Jobs Module / View

    Now we starting getting into a more code-heavy portion of this series, thankfully though this means the groundwork is all set for the most part and after adding the modules we will have a complete application that can be provided with full source. The Jobs module will have two concerns- adding and maintaining jobs that can then be broadcast out to the website. How they are displayed on the site will be handled by our admin system (which will just poll from this common database), so we aren't too concerned with that, but rather with getting the information into the system and allowing the backend administration/HR users to keep things up to date. Since there is a fair bit of information that we want to display, we're going to move editing to a separate view so we can get all that information in an easy-to-use spot. With all the files created for this module, the project looks something like this: And now... on to the code. XAML for the Job Posting View All we really need for the Job Posting View is a RadGridView and a few buttons. This will let us both show off records and perform operations on the records without much hassle. That XAML is going to look something like this: 01.<Grid x:Name="LayoutRoot" 02.Background="White"> 03.<Grid.RowDefinitions> 04.<RowDefinition Height="30" /> 05.<RowDefinition /> 06.</Grid.RowDefinitions> 07.<StackPanel Orientation="Horizontal"> 08.<Button x:Name="xAddRecordButton" 09.Content="Add Job" 10.Width="120" 11.cal:Click.Command="{Binding AddRecord}" 12.telerik:StyleManager.Theme="Windows7" /> 13.<Button x:Name="xEditRecordButton" 14.Content="Edit Job" 15.Width="120" 16.cal:Click.Command="{Binding EditRecord}" 17.telerik:StyleManager.Theme="Windows7" /> 18.</StackPanel> 19.<telerikGrid:RadGridView x:Name="xJobsGrid" 20.Grid.Row="1" 21.IsReadOnly="True" 22.AutoGenerateColumns="False" 23.ColumnWidth="*" 24.RowDetailsVisibilityMode="VisibleWhenSelected" 25.ItemsSource="{Binding MyJobs}" 26.SelectedItem="{Binding SelectedJob, Mode=TwoWay}" 27.command:SelectedItemChangedEventClass.Command="{Binding SelectedItemChanged}"> 28.<telerikGrid:RadGridView.Columns> 29.<telerikGrid:GridViewDataColumn Header="Job Title" 30.DataMemberBinding="{Binding JobTitle}" 31.UniqueName="JobTitle" /> 32.<telerikGrid:GridViewDataColumn Header="Location" 33.DataMemberBinding="{Binding Location}" 34.UniqueName="Location" /> 35.<telerikGrid:GridViewDataColumn Header="Resume Required" 36.DataMemberBinding="{Binding NeedsResume}" 37.UniqueName="NeedsResume" /> 38.<telerikGrid:GridViewDataColumn Header="CV Required" 39.DataMemberBinding="{Binding NeedsCV}" 40.UniqueName="NeedsCV" /> 41.<telerikGrid:GridViewDataColumn Header="Overview Required" 42.DataMemberBinding="{Binding NeedsOverview}" 43.UniqueName="NeedsOverview" /> 44.<telerikGrid:GridViewDataColumn Header="Active" 45.DataMemberBinding="{Binding IsActive}" 46.UniqueName="IsActive" /> 47.</telerikGrid:RadGridView.Columns> 48.</telerikGrid:RadGridView> 49.</Grid> I'll explain what's happening here by line numbers: Lines 11 and 16: Using the same type of click commands as we saw in the Menu module, we tie the button clicks to delegate commands in the viewmodel. Line 25: The source for the jobs will be a collection in the viewmodel. Line 26: We also bind the selected item to a public property from the viewmodel for use in code. Line 27: We've turned the event into a command so we can handle it via code in the viewmodel. So those first three probably make sense to you as far as Silverlight/WPF binding magic is concerned, but for line 27... This actually comes from something I read onDamien Schenkelman's blog back in the day for creating an attached behavior from any event. So, any time you see me using command:Whatever.Command, the backing for it is actually something like this: SelectedItemChangedEventBehavior.cs: 01.public class SelectedItemChangedEventBehavior : CommandBehaviorBase<Telerik.Windows.Controls.DataControl> 02.{ 03.public SelectedItemChangedEventBehavior(DataControl element) 04.: base(element) 05.{ 06.element.SelectionChanged += new EventHandler<SelectionChangeEventArgs>(element_SelectionChanged); 07.} 08.void element_SelectionChanged(object sender, SelectionChangeEventArgs e) 09.{ 10.// We'll only ever allow single selection, so will only need item index 0 11.base.CommandParameter = e.AddedItems[0]; 12.base.ExecuteCommand(); 13.} 14.} SelectedItemChangedEventClass.cs: 01.public class SelectedItemChangedEventClass 02.{ 03.#region The Command Stuff 04.public static ICommand GetCommand(DependencyObject obj) 05.{ 06.return (ICommand)obj.GetValue(CommandProperty); 07.} 08.public static void SetCommand(DependencyObject obj, ICommand value) 09.{ 10.obj.SetValue(CommandProperty, value); 11.} 12.public static readonly DependencyProperty CommandProperty = 13.DependencyProperty.RegisterAttached("Command", typeof(ICommand), 14.typeof(SelectedItemChangedEventClass), new PropertyMetadata(OnSetCommandCallback)); 15.public static void OnSetCommandCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) 16.{ 17.DataControl element = dependencyObject as DataControl; 18.if (element != null) 19.{ 20.SelectedItemChangedEventBehavior behavior = GetOrCreateBehavior(element); 21.behavior.Command = e.NewValue as ICommand; 22.} 23.} 24.#endregion 25.public static SelectedItemChangedEventBehavior GetOrCreateBehavior(DataControl element) 26.{ 27.SelectedItemChangedEventBehavior behavior = element.GetValue(SelectedItemChangedEventBehaviorProperty) as SelectedItemChangedEventBehavior; 28.if (behavior == null) 29.{ 30.behavior = new SelectedItemChangedEventBehavior(element); 31.element.SetValue(SelectedItemChangedEventBehaviorProperty, behavior); 32.} 33.return behavior; 34.} 35.public static SelectedItemChangedEventBehavior GetSelectedItemChangedEventBehavior(DependencyObject obj) 36.{ 37.return (SelectedItemChangedEventBehavior)obj.GetValue(SelectedItemChangedEventBehaviorProperty); 38.} 39.public static void SetSelectedItemChangedEventBehavior(DependencyObject obj, SelectedItemChangedEventBehavior value) 40.{ 41.obj.SetValue(SelectedItemChangedEventBehaviorProperty, value); 42.} 43.public static readonly DependencyProperty SelectedItemChangedEventBehaviorProperty = 44.DependencyProperty.RegisterAttached("SelectedItemChangedEventBehavior", 45.typeof(SelectedItemChangedEventBehavior), typeof(SelectedItemChangedEventClass), null); 46.} These end up looking very similar from command to command, but in a nutshell you create a command based on any event, determine what the parameter for it will be, then execute. It attaches via XAML and ties to a DelegateCommand in the viewmodel, so you get the full event experience (since some controls get a bit event-rich for added functionality). Simple enough, right? Viewmodel for the Job Posting View The Viewmodel is going to need to handle all events going back and forth, maintaining interactions with the data we are using, and both publishing and subscribing to events. Rather than breaking this into tons of little pieces, I'll give you a nice view of the entire viewmodel and then hit up the important points line-by-line: 001.public class JobPostingViewModel : ViewModelBase 002.{ 003.private readonly IEventAggregator eventAggregator; 004.private readonly IRegionManager regionManager; 005.public DelegateCommand<object> AddRecord { get; set; } 006.public DelegateCommand<object> EditRecord { get; set; } 007.public DelegateCommand<object> SelectedItemChanged { get; set; } 008.public RecruitingContext context; 009.private QueryableCollectionView _myJobs; 010.public QueryableCollectionView MyJobs 011.{ 012.get { return _myJobs; } 013.} 014.private QueryableCollectionView _selectionJobActionHistory; 015.public QueryableCollectionView SelectedJobActionHistory 016.{ 017.get { return _selectionJobActionHistory; } 018.} 019.private JobPosting _selectedJob; 020.public JobPosting SelectedJob 021.{ 022.get { return _selectedJob; } 023.set 024.{ 025.if (value != _selectedJob) 026.{ 027._selectedJob = value; 028.NotifyChanged("SelectedJob"); 029.} 030.} 031.} 032.public SubscriptionToken editToken = new SubscriptionToken(); 033.public SubscriptionToken addToken = new SubscriptionToken(); 034.public JobPostingViewModel(IEventAggregator eventAgg, IRegionManager regionmanager) 035.{ 036.// set Unity items 037.this.eventAggregator = eventAgg; 038.this.regionManager = regionmanager; 039.// load our context 040.context = new RecruitingContext(); 041.this._myJobs = new QueryableCollectionView(context.JobPostings); 042.context.Load(context.GetJobPostingsQuery()); 043.// set command events 044.this.AddRecord = new DelegateCommand<object>(this.AddNewRecord); 045.this.EditRecord = new DelegateCommand<object>(this.EditExistingRecord); 046.this.SelectedItemChanged = new DelegateCommand<object>(this.SelectedRecordChanged); 047.SetSubscriptions(); 048.} 049.#region DelegateCommands from View 050.public void AddNewRecord(object obj) 051.{ 052.this.eventAggregator.GetEvent<AddJobEvent>().Publish(true); 053.} 054.public void EditExistingRecord(object obj) 055.{ 056.if (_selectedJob == null) 057.{ 058.this.eventAggregator.GetEvent<NotifyUserEvent>().Publish("No job selected."); 059.} 060.else 061.{ 062.this._myJobs.EditItem(this._selectedJob); 063.this.eventAggregator.GetEvent<EditJobEvent>().Publish(this._selectedJob); 064.} 065.} 066.public void SelectedRecordChanged(object obj) 067.{ 068.if (obj.GetType() == typeof(ActionHistory)) 069.{ 070.// event bubbles up so we don't catch items from the ActionHistory grid 071.} 072.else 073.{ 074.JobPosting job = obj as JobPosting; 075.GrabHistory(job.PostingID); 076.} 077.} 078.#endregion 079.#region Subscription Declaration and Events 080.public void SetSubscriptions() 081.{ 082.EditJobCompleteEvent editComplete = eventAggregator.GetEvent<EditJobCompleteEvent>(); 083.if (editToken != null) 084.editComplete.Unsubscribe(editToken); 085.editToken = editComplete.Subscribe(this.EditCompleteEventHandler); 086.AddJobCompleteEvent addComplete = eventAggregator.GetEvent<AddJobCompleteEvent>(); 087.if (addToken != null) 088.addComplete.Unsubscribe(addToken); 089.addToken = addComplete.Subscribe(this.AddCompleteEventHandler); 090.} 091.public void EditCompleteEventHandler(bool complete) 092.{ 093.if (complete) 094.{ 095.JobPosting thisJob = _myJobs.CurrentEditItem as JobPosting; 096.this._myJobs.CommitEdit(); 097.this.context.SubmitChanges((s) => 098.{ 099.ActionHistory myAction = new ActionHistory(); 100.myAction.PostingID = thisJob.PostingID; 101.myAction.Description = String.Format("Job '{0}' has been edited by {1}", thisJob.JobTitle, "default user"); 102.myAction.TimeStamp = DateTime.Now; 103.eventAggregator.GetEvent<AddActionEvent>().Publish(myAction); 104.} 105., null); 106.} 107.else 108.{ 109.this._myJobs.CancelEdit(); 110.} 111.this.MakeMeActive(this.regionManager, "MainRegion", "JobPostingsView"); 112.} 113.public void AddCompleteEventHandler(JobPosting job) 114.{ 115.if (job == null) 116.{ 117.// do nothing, new job add cancelled 118.} 119.else 120.{ 121.this.context.JobPostings.Add(job); 122.this.context.SubmitChanges((s) => 123.{ 124.ActionHistory myAction = new ActionHistory(); 125.myAction.PostingID = job.PostingID; 126.myAction.Description = String.Format("Job '{0}' has been added by {1}", job.JobTitle, "default user"); 127.myAction.TimeStamp = DateTime.Now; 128.eventAggregator.GetEvent<AddActionEvent>().Publish(myAction); 129.} 130., null); 131.} 132.this.MakeMeActive(this.regionManager, "MainRegion", "JobPostingsView"); 133.} 134.#endregion 135.public void GrabHistory(int postID) 136.{ 137.context.ActionHistories.Clear(); 138._selectionJobActionHistory = new QueryableCollectionView(context.ActionHistories); 139.context.Load(context.GetHistoryForJobQuery(postID)); 140.} Taking it from the top, we're injecting an Event Aggregator and Region Manager for use down the road and also have the public DelegateCommands (just like in the Menu module). We also grab a reference to our context, which we'll obviously need for data, then set up a few fields with public properties tied to them. We're also setting subscription tokens, which we have not yet seen but I will get into below. The AddNewRecord (50) and EditExistingRecord (54) methods should speak for themselves for functionality, the one thing of note is we're sending events off to the Event Aggregator which some module, somewhere will take care of. Since these aren't entirely relying on one another, the Jobs View doesn't care if anyone is listening, but it will publish AddJobEvent (52), NotifyUserEvent (58) and EditJobEvent (63)regardless. Don't mind the GrabHistory() method so much, that is just grabbing history items (visibly being created in the SubmitChanges callbacks), and adding them to the database. Every action will trigger a history event, so we'll know who modified what and when, just in case. ;) So where are we at? Well, if we click to Add a job, we publish an event, if we edit a job, we publish an event with the selected record (attained through the magic of binding). Where is this all going though? To the Viewmodel, of course! XAML for the AddEditJobView This is pretty straightforward except for one thing, noted below: 001.<Grid x:Name="LayoutRoot" 002.Background="White"> 003.<Grid x:Name="xEditGrid" 004.Margin="10" 005.validationHelper:ValidationScope.Errors="{Binding Errors}"> 006.<Grid.Background> 007.<LinearGradientBrush EndPoint="0.5,1" 008.StartPoint="0.5,0"> 009.<GradientStop Color="#FFC7C7C7" 010.Offset="0" /> 011.<GradientStop Color="#FFF6F3F3" 012.Offset="1" /> 013.</LinearGradientBrush> 014.</Grid.Background> 015.<Grid.RowDefinitions> 016.<RowDefinition Height="40" /> 017.<RowDefinition Height="40" /> 018.<RowDefinition Height="40" /> 019.<RowDefinition Height="100" /> 020.<RowDefinition Height="100" /> 021.<RowDefinition Height="100" /> 022.<RowDefinition Height="40" /> 023.<RowDefinition Height="40" /> 024.<RowDefinition Height="40" /> 025.</Grid.RowDefinitions> 026.<Grid.ColumnDefinitions> 027.<ColumnDefinition Width="150" /> 028.<ColumnDefinition Width="150" /> 029.<ColumnDefinition Width="300" /> 030.<ColumnDefinition Width="100" /> 031.</Grid.ColumnDefinitions> 032.<!-- Title --> 033.<TextBlock Margin="8" 034.Text="{Binding AddEditString}" 035.TextWrapping="Wrap" 036.Grid.Column="1" 037.Grid.ColumnSpan="2" 038.FontSize="16" /> 039.<!-- Data entry area--> 040. 041.<TextBlock Margin="8,0,0,0" 042.Style="{StaticResource LabelTxb}" 043.Grid.Row="1" 044.Text="Job Title" 045.VerticalAlignment="Center" /> 046.<TextBox x:Name="xJobTitleTB" 047.Margin="0,8" 048.Grid.Column="1" 049.Grid.Row="1" 050.Text="{Binding activeJob.JobTitle, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 051.Grid.ColumnSpan="2" /> 052.<TextBlock Margin="8,0,0,0" 053.Grid.Row="2" 054.Text="Location" 055.d:LayoutOverrides="Height" 056.VerticalAlignment="Center" /> 057.<TextBox x:Name="xLocationTB" 058.Margin="0,8" 059.Grid.Column="1" 060.Grid.Row="2" 061.Text="{Binding activeJob.Location, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 062.Grid.ColumnSpan="2" /> 063. 064.<TextBlock Margin="8,11,8,0" 065.Grid.Row="3" 066.Text="Description" 067.TextWrapping="Wrap" 068.VerticalAlignment="Top" /> 069. 070.<TextBox x:Name="xDescriptionTB" 071.Height="84" 072.TextWrapping="Wrap" 073.ScrollViewer.VerticalScrollBarVisibility="Auto" 074.Grid.Column="1" 075.Grid.Row="3" 076.Text="{Binding activeJob.Description, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 077.Grid.ColumnSpan="2" /> 078.<TextBlock Margin="8,11,8,0" 079.Grid.Row="4" 080.Text="Requirements" 081.TextWrapping="Wrap" 082.VerticalAlignment="Top" /> 083. 084.<TextBox x:Name="xRequirementsTB" 085.Height="84" 086.TextWrapping="Wrap" 087.ScrollViewer.VerticalScrollBarVisibility="Auto" 088.Grid.Column="1" 089.Grid.Row="4" 090.Text="{Binding activeJob.Requirements, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 091.Grid.ColumnSpan="2" /> 092.<TextBlock Margin="8,11,8,0" 093.Grid.Row="5" 094.Text="Qualifications" 095.TextWrapping="Wrap" 096.VerticalAlignment="Top" /> 097. 098.<TextBox x:Name="xQualificationsTB" 099.Height="84" 100.TextWrapping="Wrap" 101.ScrollViewer.VerticalScrollBarVisibility="Auto" 102.Grid.Column="1" 103.Grid.Row="5" 104.Text="{Binding activeJob.Qualifications, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" 105.Grid.ColumnSpan="2" /> 106.<!-- Requirements Checkboxes--> 107. 108.<CheckBox x:Name="xResumeRequiredCB" Margin="8,8,8,15" 109.Content="Resume Required" 110.Grid.Row="6" 111.Grid.ColumnSpan="2" 112.IsChecked="{Binding activeJob.NeedsResume, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> 113. 114.<CheckBox x:Name="xCoverletterRequiredCB" Margin="8,8,8,15" 115.Content="Cover Letter Required" 116.Grid.Column="2" 117.Grid.Row="6" 118.IsChecked="{Binding activeJob.NeedsCV, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> 119. 120.<CheckBox x:Name="xOverviewRequiredCB" Margin="8,8,8,15" 121.Content="Overview Required" 122.Grid.Row="7" 123.Grid.ColumnSpan="2" 124.IsChecked="{Binding activeJob.NeedsOverview, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> 125. 126.<CheckBox x:Name="xJobActiveCB" Margin="8,8,8,15" 127.Content="Job is Active" 128.Grid.Column="2" 129.Grid.Row="7" 130.IsChecked="{Binding activeJob.IsActive, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/> 131. 132.<!-- Buttons --> 133. 134.<Button x:Name="xAddEditButton" Margin="8,8,0,10" 135.Content="{Binding AddEditButtonString}" 136.cal:Click.Command="{Binding AddEditCommand}" 137.Grid.Column="2" 138.Grid.Row="8" 139.HorizontalAlignment="Left" 140.Width="125" 141.telerik:StyleManager.Theme="Windows7" /> 142. 143.<Button x:Name="xCancelButton" HorizontalAlignment="Right" 144.Content="Cancel" 145.cal:Click.Command="{Binding CancelCommand}" 146.Margin="0,8,8,10" 147.Width="125" 148.Grid.Column="2" 149.Grid.Row="8" 150.telerik:StyleManager.Theme="Windows7" /> 151.</Grid> 152.</Grid> The 'validationHelper:ValidationScope' line may seem odd. This is a handy little trick for catching current and would-be validation errors when working in this whole setup. This all comes from an approach found on theJoy Of Code blog, although it looks like the story for this will be changing slightly with new advances in SL4/WCF RIA Services, so this section can definitely get an overhaul a little down the road. The code is the fun part of all this, so let us see what's happening under the hood. Viewmodel for the AddEditJobView We are going to see some of the same things happening here, so I'll skip over the repeat info and get right to the good stuff: 001.public class AddEditJobViewModel : ViewModelBase 002.{ 003.private readonly IEventAggregator eventAggregator; 004.private readonly IRegionManager regionManager; 005. 006.public RecruitingContext context; 007. 008.private JobPosting _activeJob; 009.public JobPosting activeJob 010.{ 011.get { return _activeJob; } 012.set 013.{ 014.if (_activeJob != value) 015.{ 016._activeJob = value; 017.NotifyChanged("activeJob"); 018.} 019.} 020.} 021. 022.public bool isNewJob; 023. 024.private string _addEditString; 025.public string AddEditString 026.{ 027.get { return _addEditString; } 028.set 029.{ 030.if (_addEditString != value) 031.{ 032._addEditString = value; 033.NotifyChanged("AddEditString"); 034.} 035.} 036.} 037. 038.private string _addEditButtonString; 039.public string AddEditButtonString 040.{ 041.get { return _addEditButtonString; } 042.set 043.{ 044.if (_addEditButtonString != value) 045.{ 046._addEditButtonString = value; 047.NotifyChanged("AddEditButtonString"); 048.} 049.} 050.} 051. 052.public SubscriptionToken addJobToken = new SubscriptionToken(); 053.public SubscriptionToken editJobToken = new SubscriptionToken(); 054. 055.public DelegateCommand<object> AddEditCommand { get; set; } 056.public DelegateCommand<object> CancelCommand { get; set; } 057. 058.private ObservableCollection<ValidationError> _errors = new ObservableCollection<ValidationError>(); 059.public ObservableCollection<ValidationError> Errors 060.{ 061.get { return _errors; } 062.} 063. 064.private ObservableCollection<ValidationResult> _valResults = new ObservableCollection<ValidationResult>(); 065.public ObservableCollection<ValidationResult> ValResults 066.{ 067.get { return this._valResults; } 068.} 069. 070.public AddEditJobViewModel(IEventAggregator eventAgg, IRegionManager regionmanager) 071.{ 072.// set Unity items 073.this.eventAggregator = eventAgg; 074.this.regionManager = regionmanager; 075. 076.context = new RecruitingContext(); 077. 078.AddEditCommand = new DelegateCommand<object>(this.AddEditJobCommand); 079.CancelCommand = new DelegateCommand<object>(this.CancelAddEditCommand); 080. 081.SetSubscriptions(); 082.} 083. 084.#region Subscription Declaration and Events 085. 086.public void SetSubscriptions() 087.{ 088.AddJobEvent addJob = this.eventAggregator.GetEvent<AddJobEvent>(); 089. 090.if (addJobToken != null) 091.addJob.Unsubscribe(addJobToken); 092. 093.addJobToken = addJob.Subscribe(this.AddJobEventHandler); 094. 095.EditJobEvent editJob = this.eventAggregator.GetEvent<EditJobEvent>(); 096. 097.if (editJobToken != null) 098.editJob.Unsubscribe(editJobToken); 099. 100.editJobToken = editJob.Subscribe(this.EditJobEventHandler); 101.} 102. 103.public void AddJobEventHandler(bool isNew) 104.{ 105.this.activeJob = null; 106.this.activeJob = new JobPosting(); 107.this.activeJob.IsActive = true; // We assume that we want a new job to go up immediately 108.this.isNewJob = true; 109.this.AddEditString = "Add New Job Posting"; 110.this.AddEditButtonString = "Add Job"; 111. 112.MakeMeActive(this.regionManager, "MainRegion", "AddEditJobView"); 113.} 114. 115.public void EditJobEventHandler(JobPosting editJob) 116.{ 117.this.activeJob = null; 118.this.activeJob = editJob; 119.this.isNewJob = false; 120.this.AddEditString = "Edit Job Posting"; 121.this.AddEditButtonString = "Edit Job"; 122. 123.MakeMeActive(this.regionManager, "MainRegion", "AddEditJobView"); 124.} 125. 126.#endregion 127. 128.#region DelegateCommands from View 129. 130.public void AddEditJobCommand(object obj) 131.{ 132.if (this.Errors.Count > 0) 133.{ 134.List<string> errorMessages = new List<string>(); 135. 136.foreach (var valR in this.Errors) 137.{ 138.errorMessages.Add(valR.Exception.Message); 139.} 140. 141.this.eventAggregator.GetEvent<DisplayValidationErrorsEvent>().Publish(errorMessages); 142. 143.} 144.else if (!Validator.TryValidateObject(this.activeJob, new ValidationContext(this.activeJob, null, null), _valResults, true)) 145.{ 146.List<string> errorMessages = new List<string>(); 147. 148.foreach (var valR in this._valResults) 149.{ 150.errorMessages.Add(valR.ErrorMessage); 151.} 152. 153.this._valResults.Clear(); 154. 155.this.eventAggregator.GetEvent<DisplayValidationErrorsEvent>().Publish(errorMessages); 156.} 157.else 158.{ 159.if (this.isNewJob) 160.{ 161.this.eventAggregator.GetEvent<AddJobCompleteEvent>().Publish(this.activeJob); 162.} 163.else 164.{ 165.this.eventAggregator.GetEvent<EditJobCompleteEvent>().Publish(true); 166.} 167.} 168.} 169. 170.public void CancelAddEditCommand(object obj) 171.{ 172.if (this.isNewJob) 173.{ 174.this.eventAggregator.GetEvent<AddJobCompleteEvent>().Publish(null); 175.} 176.else 177.{ 178.this.eventAggregator.GetEvent<EditJobCompleteEvent>().Publish(false); 179.} 180.} 181. 182.#endregion 183.} 184.} We start seeing something new on line 103- the AddJobEventHandler will create a new job and set that to the activeJob item on the ViewModel. When this is all set, the view calls that familiar MakeMeActive method to activate itself. I made a bit of a management call on making views self-activate like this, but I figured it works for one reason. As I create this application, views may not exist that I have in mind, so after a view receives its 'ping' from being subscribed to an event, it prepares whatever it needs to do and then goes active. This way if I don't have 'edit' hooked up, I can click as the day is long on the main view and won't get lost in an empty region. Total personal preference here. :) Everything else should again be pretty straightforward, although I do a bit of validation checking in the AddEditJobCommand, which can either fire off an event back to the main view/viewmodel if everything is a success or sent a list of errors to our notification module, which pops open a RadWindow with the alerts if any exist. As a bonus side note, here's what my WCF RIA Services metadata looks like for handling all of the validation: private JobPostingMetadata() { } [StringLength(2500, ErrorMessage = "Description should be more than one and less than 2500 characters.", MinimumLength = 1)] [Required(ErrorMessage = "Description is required.")] public string Description; [Required(ErrorMessage="Active Status is Required")] public bool IsActive; [StringLength(100, ErrorMessage = "Posting title must be more than 3 but less than 100 characters.", MinimumLength = 3)] [Required(ErrorMessage = "Job Title is required.")] public bool JobTitle; [Required] public string Location; public bool NeedsCV; public bool NeedsOverview; public bool NeedsResume; public int PostingID; [Required(ErrorMessage="Qualifications are required.")] [StringLength(2500, ErrorMessage="Qualifications should be more than one and less than 2500 characters.", MinimumLength=1)] public string Qualifications; [StringLength(2500, ErrorMessage = "Requirements should be more than one and less than 2500 characters.", MinimumLength = 1)] [Required(ErrorMessage="Requirements are required.")] public string Requirements;   The RecruitCB Alternative See all that Xaml I pasted above? Those are now two pieces sitting in the JobsView.xaml file now. The only real difference is that the xEditGrid now sits in the same place as xJobsGrid, with visibility swapping out between the two for a quick switch. I also took out all the cal: and command: command references and replaced Button events with clicks and the Grid selection command replaced with a SelectedItemChanged event. Also, at the bottom of the xEditGrid after the last button, I add a ValidationSummary (with Visibility=Collapsed) to catch any errors that are popping up. Simple as can be, and leads to this being the single code-behind file: 001.public partial class JobsView : UserControl 002.{ 003.public RecruitingContext context; 004.public JobPosting activeJob; 005.public bool isNew; 006.private ObservableCollection<ValidationResult> _valResults = new ObservableCollection<ValidationResult>(); 007.public ObservableCollection<ValidationResult> ValResults 008.{ 009.get { return this._valResults; } 010.} 011.public JobsView() 012.{ 013.InitializeComponent(); 014.this.Loaded += new RoutedEventHandler(JobsView_Loaded); 015.} 016.void JobsView_Loaded(object sender, RoutedEventArgs e) 017.{ 018.context = new RecruitingContext(); 019.xJobsGrid.ItemsSource = context.JobPostings; 020.context.Load(context.GetJobPostingsQuery()); 021.} 022.private void xAddRecordButton_Click(object sender, RoutedEventArgs e) 023.{ 024.activeJob = new JobPosting(); 025.isNew = true; 026.xAddEditTitle.Text = "Add a Job Posting"; 027.xAddEditButton.Content = "Add"; 028.xEditGrid.DataContext = activeJob; 029.HideJobsGrid(); 030.} 031.private void xEditRecordButton_Click(object sender, RoutedEventArgs e) 032.{ 033.activeJob = xJobsGrid.SelectedItem as JobPosting; 034.isNew = false; 035.xAddEditTitle.Text = "Edit a Job Posting"; 036.xAddEditButton.Content = "Edit"; 037.xEditGrid.DataContext = activeJob; 038.HideJobsGrid(); 039.} 040.private void xAddEditButton_Click(object sender, RoutedEventArgs e) 041.{ 042.if (!Validator.TryValidateObject(this.activeJob, new ValidationContext(this.activeJob, null, null), _valResults, true)) 043.{ 044.List<string> errorMessages = new List<string>(); 045.foreach (var valR in this._valResults) 046.{ 047.errorMessages.Add(valR.ErrorMessage); 048.} 049.this._valResults.Clear(); 050.ShowErrors(errorMessages); 051.} 052.else if (xSummary.Errors.Count > 0) 053.{ 054.List<string> errorMessages = new List<string>(); 055.foreach (var err in xSummary.Errors) 056.{ 057.errorMessages.Add(err.Message); 058.} 059.ShowErrors(errorMessages); 060.} 061.else 062.{ 063.if (this.isNew) 064.{ 065.context.JobPostings.Add(activeJob); 066.context.SubmitChanges((s) => 067.{ 068.ActionHistory thisAction = new ActionHistory(); 069.thisAction.PostingID = activeJob.PostingID; 070.thisAction.Description = String.Format("Job '{0}' has been edited by {1}", activeJob.JobTitle, "default user"); 071.thisAction.TimeStamp = DateTime.Now; 072.context.ActionHistories.Add(thisAction); 073.context.SubmitChanges(); 074.}, null); 075.} 076.else 077.{ 078.context.SubmitChanges((s) => 079.{ 080.ActionHistory thisAction = new ActionHistory(); 081.thisAction.PostingID = activeJob.PostingID; 082.thisAction.Description = String.Format("Job '{0}' has been added by {1}", activeJob.JobTitle, "default user"); 083.thisAction.TimeStamp = DateTime.Now; 084.context.ActionHistories.Add(thisAction); 085.context.SubmitChanges(); 086.}, null); 087.} 088.ShowJobsGrid(); 089.} 090.} 091.private void xCancelButton_Click(object sender, RoutedEventArgs e) 092.{ 093.ShowJobsGrid(); 094.} 095.private void ShowJobsGrid() 096.{ 097.xAddEditRecordButtonPanel.Visibility = Visibility.Visible; 098.xEditGrid.Visibility = Visibility.Collapsed; 099.xJobsGrid.Visibility = Visibility.Visible; 100.} 101.private void HideJobsGrid() 102.{ 103.xAddEditRecordButtonPanel.Visibility = Visibility.Collapsed; 104.xJobsGrid.Visibility = Visibility.Collapsed; 105.xEditGrid.Visibility = Visibility.Visible; 106.} 107.private void ShowErrors(List<string> errorList) 108.{ 109.string nm = "Errors received: \n"; 110.foreach (string anerror in errorList) 111.nm += anerror + "\n"; 112.RadWindow.Alert(nm); 113.} 114.} The first 39 lines should be pretty familiar, not doing anything too unorthodox to get this up and running. Once we hit the xAddEditButton_Click on line 40, we're still doing pretty much the same things except instead of checking the ValidationHelper errors, we both run a check on the current activeJob object as well as check the ValidationSummary errors list. Once that is set, we again use the callback of context.SubmitChanges (lines 68 and 78) to create an ActionHistory which we will use to track these items down the line. That's all? Essentially... yes. If you look back through this post, most of the code and adventures we have taken were just to get things working in the MVVM/Prism setup. Since I have the whole 'module' self-contained in a single JobView+code-behind setup, I don't have to worry about things like sending events off into space for someone to pick up, communicating through an Infrastructure project, or even re-inventing events to be used with attached behaviors. Everything just kinda works, and again with much less code. Here's a picture of the MVVM and Code-behind versions on the Jobs and AddEdit views, but since the functionality is the same in both apps you still cannot tell them apart (for two-strike): Looking ahead, the Applicants module is effectively the same thing as the Jobs module, so most of the code is being cut-and-pasted back and forth with minor tweaks here and there. So that one is being taken care of by me behind the scenes. Next time, we get into a new world of fun- the interview scheduling module, which will pull from available jobs and applicants for each interview being scheduled, tying everything together with RadScheduler to the rescue. Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • How to retrive message list from p2p

    - by cre-johnny07
    Hello friends I have a messaging system that uses p2p. Each peer has a incoming message list and a outgoing message list. What I need to do is whenever a new peer will join the mesh he will get the all the incoming messages from other peers and add those into it's own incoming message list. Now I know when I get the other peer info from I can ask them to give their own list to me. But I'm not finding the way how..? Any suggestion on this or help would be highly appreciated. I'm giving my code below. Thanking in Advance Johnny #region Instance Fields private string strOrigin = ""; //the chat member name private string m_Member; //the channel instance where we execute our service methods against private IServerChannel m_participant; //the instance context which in this case is our window since it is the service host private InstanceContext m_site; //our binding transport for the p2p mesh private NetPeerTcpBinding m_binding; //the factory to create our chat channel private ChannelFactory<IServerChannel> m_channelFactory; //an interface provided by the channel exposing events to indicate //when we have connected or disconnected from the mesh private IOnlineStatus o_statusHandler; //a generic delegate to execute a thread against that accepts no args private delegate void NoArgDelegate(); //an object to hold user details private IUserService userService; //an Observable Collection of object to get all the Application Instance Details in databas ObservableCollection<AppLoginInstance> appLoginInstances; // an Observable Collection of object to get all Incoming Messages types ObservableCollection<MessageType> inComingMessageTypes; // an Observable Collection of object to get all Outgoing Messages ObservableCollection<PDCL.ERP.DataModels.Message> outGoingMessages; // an Observable Collection of object to get all Incoming Messages ObservableCollection<PDCL.ERP.DataModels.Message> inComingMessages; //an Event Aggregator to publish event for other modules to subscribe private readonly IEventAggregator eventAggregator; /// <summary> /// an IUnityCOntainer to get the container /// </summary> private IUnityContainer container; private RefreshConnectionStatus refreshConnectionStatus; private RefreshConnectionStatusEventArgs args; private ReplyRequestMessage replyMessageRequest; private ReplyRequestMessageEventArgs eventsArgs; #endregion public P2pMessageService(IUserService UserService, IEventAggregator EventAggregator, IUnityContainer container) { userService = UserService; this.container = container; appLoginInstances = new ObservableCollection<AppLoginInstance>(); inComingMessageTypes = new ObservableCollection<MessageType>(); inComingMessages = new ObservableCollection<PDCL.ERP.DataModels.Message>(); outGoingMessages = new ObservableCollection<PDCL.ERP.DataModels.Message>(); this.args = new RefreshConnectionStatusEventArgs(); this.eventsArgs = new ReplyRequestMessageEventArgs(); this.eventAggregator = EventAggregator; this.refreshConnectionStatus = this.eventAggregator.GetEvent<RefreshConnectionStatus>(); this.replyMessageRequest = this.eventAggregator.GetEvent<ReplyRequestMessage>(); } #region IOnlineStatus Event Handlers void ostat_Offline(object sender, EventArgs e) { // we could update a status bar or animate an icon to //indicate to the user they have disconnected from the mesh //currently i don't have a "disconnect" button but adding it //should be trivial if you understand the rest of this code } void ostat_Online(object sender, EventArgs e) { try { m_participant.Join(userService.AppInstance); } catch (Exception Ex) { Logger.Exception(Ex, Ex.TargetSite.Name + ": " + Ex.TargetSite + ": " + Ex.Message); } } #endregion #region IServer Members //this method gets called from a background thread to //connect the service client to the p2p mesh specified //by the binding info in the app.config public void ConnectToMesh() { try { m_site = new InstanceContext(this); //use the binding from the app.config with default settings m_binding = new NetPeerTcpBinding("P2PMessageBinding"); m_channelFactory = new DuplexChannelFactory<IServerChannel>(m_site, "P2PMessageEndPoint"); m_participant = m_channelFactory.CreateChannel(); o_statusHandler = m_participant.GetProperty<IOnlineStatus>(); o_statusHandler.Online += new EventHandler(ostat_Online); o_statusHandler.Offline += new EventHandler(ostat_Offline); //m_participant.InitializeMesh(); //this.appLoginInstances.Add(this.userService.AppInstance); BackgroundWorkerHelper.DoWork<object>(() => { //this is an empty unhandled method on the service interface. //why? because for some reason p2p clients don't try to connect to the mesh //until the first service method call. so to facilitate connecting i call this method //to get the ball rolling. m_participant.InitializeMesh(); //SynchronizeMessage(this.inComingMessages); return new object(); }, arg => { }); this.appLoginInstances.Add(this.userService.AppInstance); } catch (Exception Ex) { Logger.Exception(Ex, Ex.TargetSite.Name + ": " + Ex.TargetSite + ": " + Ex.Message); } } public void Join(AppLoginInstance obj) { try { // Adding Instance to the PeerList if (appLoginInstances.SingleOrDefault(a => a.InstanceId == obj.InstanceId)==null) { appLoginInstances.Add(obj); this.refreshConnectionStatus.Publish(new RefreshConnectionStatusEventArgs() { Status = m_channelFactory.State }); } //this will retrieve any new members that have joined before the current user m_participant.SynchronizeMemberList(userService.AppInstance); } catch(Exception Ex) { Logger.Exception(Ex,Ex.TargetSite.Name + ": " + Ex.TargetSite + ": " + Ex.Message); } } /// <summary> /// Synchronizes member list /// </summary> /// <param name="obj">The AppLoginInstance Param</param> public void SynchronizeMemberList(AppLoginInstance obj) { //as member names come in we simply disregard duplicates and //add them to the member list, this way we can retrieve a list //of members already in the chatroom when we enter at any time. //again, since this is just an example this is the simplified //way to do things. the correct way would be to retrieve a list //of peernames and retrieve the metadata from each one which would //tell us what the member name is and add it. we would want to check //this list when we join the mesh to make sure our member name doesn't //conflict with someone else try { if (appLoginInstances.SingleOrDefault(a => a.InstanceId == obj.InstanceId) == null) { appLoginInstances.Add(obj); } } catch (Exception Ex) { Logger.Exception(Ex, Ex.TargetSite.Name + ": " + Ex.TargetSite + ": " + Ex.Message); } } /// <summary> /// This methos broadcasts the mesasge to all peers. /// </summary> /// <param name="msg">The whole message which is to be broadcasted</param> /// <param name="securityLevels"> Level of security</param> public void BroadCastMsg(PDCL.ERP.DataModels.Message msg, List<string> securityLevels) { try { foreach (string s in securityLevels) { if (this.userService.IsInRole(s)) { if (this.inComingMessages.Count == 0 && msg.CreatedByApp != this.userService.AppInstanceId) { this.inComingMessages.Add(msg); } else if (this.inComingMessages.SingleOrDefault(a => a.MessageId == msg.MessageId) == null && msg.CreatedByApp != this.userService.AppInstanceId) { this.inComingMessages.Add(msg); } } } } catch (Exception Ex) { Logger.Exception(Ex, Ex.TargetSite.Name + ": " + Ex.TargetSite + ": " + Ex.Message); } } /// <summary> /// /// </summary> /// <param name="msg">The Message to denyed</param> public void BroadCastReplyMsg(PDCL.ERP.DataModels.Message msg) { try { //if (this.inComingMessages.SingleOrDefault(a => a.MessageId == msg.MessageId) != null) //{ this.replyMessageRequest.Publish(new ReplyRequestMessageEventArgs() { Message = msg }); this.inComingMessages.Remove(this.inComingMessages.SingleOrDefault(o => o.MessageId == msg.MessageId)); //} } catch (Exception ex) { Logger.Exception(ex, ex.TargetSite.Name + ": " + ex.TargetSite + ": " + ex.Message); } } //again we need to sync the worker thread with the UI thread via Dispatcher public void Whisper(string Member, string MemberTo, string Message) { } public void InitializeMesh() { //do nothing } public void Leave(AppLoginInstance obj) { if (this.appLoginInstances.SingleOrDefault(a => a.InstanceId == obj.InstanceId) != null) { this.appLoginInstances.Remove(this.appLoginInstances.Single(a => a.InstanceId == obj.InstanceId)); } } //public void SynchronizeRemoveMemberList(AppLoginInstance obj) //{ // if (appLoginInstances.SingleOrDefault(a => a.InstanceId == obj.InstanceId) != null) // { // appLoginInstances.Remove(obj); // } //} #endregion

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >