Search Results

Search found 100 results on 4 pages for 'icommand'.

Page 3/4 | < Previous Page | 1 2 3 4  | Next Page >

  • Including partial views when applying the Mode-View-ViewModel design pattern

    - by Filip Ekberg
    Consider that I have an application that just handles Messages and Users I want my Window to have a common Menu and an area where the current View is displayed. I can only work with either Messages or Users so I cannot work simultaniously with both Views. Therefore I have the following Controls MessageView.xaml UserView.xaml Just to make it a bit easier, both the Message Model and the User Model looks like this: Name Description Now, I have the following three ViewModels: MainWindowViewModel UsersViewModel MessagesViewModel The UsersViewModel and the MessagesViewModel both just fetch an ObserverableCollection<T> of its regarding Model which is bound in the corresponding View like this: <DataGrid ItemSource="{Binding ModelCollection}" /> The MainWindowViewModel hooks up two different Commands that have implemented ICommand that looks something like the following: public class ShowMessagesCommand : ICommand { private ViewModelBase ViewModel { get; set; } public ShowMessagesCommand (ViewModelBase viewModel) { ViewModel = viewModel; } public void Execute(object parameter) { var viewModel = new ProductsViewModel(); ViewModel.PartialViewModel = new MessageView { DataContext = viewModel }; } public bool CanExecute(object parameter) { return true; } public event EventHandler CanExecuteChanged; } And there is another one a like it that will show Users. Now this introduced ViewModelBase which only holds the following: public UIElement PartialViewModel { get { return (UIElement)GetValue(PartialViewModelProperty); } set { SetValue(PartialViewModelProperty, value); } } public static readonly DependencyProperty PartialViewModelProperty = DependencyProperty.Register("PartialViewModel", typeof(UIElement), typeof(ViewModelBase), new UIPropertyMetadata(null)); This dependency property is used in the MainWindow.xaml to display the User Control dynamicly like this: <UserControl Content="{Binding PartialViewModel}" /> There are also two buttons on this Window that fires the Commands: ShowMessagesCommand ShowUsersCommand And when these are fired, the UserControl changes because PartialViewModel is a dependency property. I want to know if this is bad practice? Should I not inject the User Control like this? Is there another "better" alternative that corresponds better with the design pattern? Or is this a nice way of including partial views?

    Read the article

  • Diff/Merge functionality for objects (not files!)

    - by gehho
    I have a collection of objects of the same type, let's call it DataItem. The user can view and edit these items in an editor. It should also be possible to compare and merge different items, i.e. some sort of diff/merge for DataItem instances. The DIFF functionality should compare all (relevant) properties/fields of the items and detect possible differences. The MERGE functionality should then be able to merge two instances by applying selected differences to one of the items. For example (pseudo objects): DataItem1 { DataItem2 { Prop1 = 10 Prop1 = 10 Prop2 = 25 Prop2 = 13 Prop3 = 0 Prop3 = 5 Coll = { 7, 4, 8 } Coll = { 7, 4, 8, 12 } } } Now, the user should be provided with a list of differences (i.e. Prop2, Prop3, and Coll) and he should be able to select which differences he wants to eliminate by assigning the value from one item to the other. He should also be able to choose if he wants to assign the value from DataItem1 to DataItem2 or vice versa. Are there common practices which should be used to implement this functionality? Since the same editor should also provide undo/redo functionality (using the Command pattern), I was thinking about reusing the ICommand implementations because both scenarios basically handle with property assignments, collection changes, and so on... My idea was to create Difference objects with ICommand properties which can be used to perform a merge operation for this specific Difference. Btw: The programming language will be C# with .NET 3.5SP1/4.0. However, I think this is more of a language-independent question. Any design pattern/idea/whatsoever is welcome!

    Read the article

  • International Radio Operators Alphabet in F# &amp; Silverlight &ndash; Part 2

    - by MarkPearl
    So the brunt of my my very complex F# code has been done. Now it’s just putting the Silverlight stuff in. The first thing I did was add a new project to my solution. I gave it a name and VS2010 did the rest of the magic in creating the .Web project etc. In this instance because I want to take the MVVM approach and make use of commanding I have decided to make the frontend a Silverlight4 project. I now need move my F# code into a proper Silverlight Library. Warning – when you create the Silverlight Library VS2010 will ask you whether you want it to be based on Silverlight3 or Silverlight4. I originally went for Silverlight4 only to discover when I tried to compile my solution that I was given an error… Error 12 F# runtime for Silverlight version v4.0 is not installed. Please go to http://go.microsoft.com/fwlink/?LinkId=177463 to download and install matching.. After asking around I discovered that the Silverlight4 F# runtime is not available yet. No problem, the suggestion was to change the F# Silverlight Library to a Silverlight3 project however when going to the properties of the project file – even though I changed it to Silverlight3, VS2010 did not like it and kept reverting it to a Silverlight4 project. After a few minutes of scratching my head I simply deleted Silverlight4 F# Library project and created a new F# Silverlight Library project in Silverlight3 and VS2010 was happy. Now that the project structure is set up, rest is fairly simple. You need to add the Silverlight Library as a reference to the C# Silverlight Front End. Then setup your views, since I was following the MVVM pattern I made a Views & ViewModel folder and set up the relevant View and ViewModels. The MainPageViewModel file looks as follows using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Collections.ObjectModel; namespace IROAFrontEnd.ViewModels { public class MainPageViewModel : ViewModelBase { private string _iroaString; private string _inputCharacters; public string InputCharacters { get { return _inputCharacters; } set { if (_inputCharacters != value) { _inputCharacters = value; OnPropertyChanged("InputCharacters"); } } } public string IROAString { get { return _iroaString; } set { if (_iroaString != value) { _iroaString = value; OnPropertyChanged("IROAString"); } } } public ICommand MySpecialCommand { get { return new MyCommand(this); } } public class MyCommand : ICommand { readonly MainPageViewModel _myViewModel; public MyCommand(MainPageViewModel myViewModel) { _myViewModel = myViewModel; } public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { var result = ModuleMain.ConvertCharsToStrings(_myViewModel.InputCharacters); var newString = ""; foreach (var Item in result) { newString += Item + " "; } _myViewModel.IROAString = newString.Trim(); } } } } One of the features I like in Silverlight4 is the new commanding. You will notice in my I have put the code under the command execute to reference to my F# module. At the moment this could be cleaned up even more, but will suffice for now.. public void Execute(object parameter) { var result = ModuleMain.ConvertCharsToStrings(_myViewModel.InputCharacters); var newString = ""; foreach (var Item in result) { newString += Item + " "; } _myViewModel.IROAString = newString.Trim(); } I then needed to set the view up. If we have a look at the MainPageView.xaml the xaml code will look like the following…. Nothing to fancy, but battleship grey for now… take careful note of the binding of the command in the button to MySpecialCommand which was created in the ViewModel. <UserControl x:Class="IROAFrontEnd.Views.MainPageView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400"> <Grid x:Name="LayoutRoot" Background="White"> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <TextBox Grid.Row="0" Text="{Binding InputCharacters, Mode=TwoWay}"/> <Button Grid.Row="1" Command="{Binding MySpecialCommand}"> <TextBlock Text="Generate"/> </Button> <TextBlock Grid.Row="2" Text="{Binding IROAString}"/> </Grid> </UserControl> Finally in the App.xaml.cs file we need to set the View and link it to the ViewModel. private void Application_Startup(object sender, StartupEventArgs e) { var myView = new MainPageView(); var myViewModel = new MainPageViewModel(); myView.DataContext = myViewModel; this.RootVisual = myView; }   Once this is done – hey presto – it worked. I typed in some “Test Input” and clicked the generate button and the correct Radio Operators Alphabet was generated. And that’s the end of my first very basic F# Silverlight application.

    Read the article

  • The Grand Unified Framework Theory

    Tom Janssens left a comment: What still bugs me is that we do not have a unified pattern for all .net dev (using modelbinders and icommand for example...) But, Tom we are pretty close. At least as close as we should be, I think. With .NET there are plenty of low level patterns we can reuse regardless of the application platform or architecture. Stuff like: Asynchronous programming with events or the TPL. Object queries with LINQ. Resource management with IDispose. At a higher...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

  • Can Spring.Net function as PostSharp?

    - by Alex K
    A few months back I've discovered PostSharp, and for a time, it was good. But then legal came back with an answer saying that they don't like the licence of the old versions. Then the department told me that 2.0's price was unacceptably high (for the number of seats we need)... I was extremely disapponted, but not disheartened. Can't be the only such framework, I thought. I kept looking for a replacement, but most of it was either dead, ill maintained (especially in documentation department), for academic use, or all of the above (I'm looking at you Aspect.Net) Then I've discovered Spring.Net, and for a time, it was good. I've been reading the documentation and it went on to paint what seemed to be a supperior picture of an AOP nirvana. No longer was I locked to attributes to mark where I wanted code interception to take place, but it could be configured in XML and changes to it didn't require re-compile. Great. Then I looked at the samples and saw the following, in every single usage scenario: // Create AOP proxy using Spring.NET IoC container. IApplicationContext ctx = ContextRegistry.GetContext(); ICommand command = (ICommand)ctx["myServiceCommand"]; command.Execute(); if (command.IsUndoCapable) { command.UnExecute(); } Why must the first two lines of code exist? It ruins everything. This means I cannot simply provide a user with a set of aspects and attributes or XML configs that they can use by sticking appropriate attributes on the appropriate methods/classes/etc or editing the match pattern in XML. They have to modify their program logic to make this work! Is there a way to make Spring.Net behave as PostSharp in this case? (i.e. user only needs to add attributes/XML config, not edit content of any methods. Alternatively, is there a worthy and functioning alternative to PostSharp? I've seen a few question titled like this on SO, but none of them were actually looking to replace PostSharp, they only wanted to supplement its functionality. I need full replacement.

    Read the article

  • Prism Commands - binding error when binding to list element ?

    - by Maciek
    I've got a ItemsControl (to be replaced by listbox) which has it's ItemsSource bound to an ObservableCollection<User> which is located in the view model. The View Model contains some DelegateCommand<T> delegates for handling commands (for instance UpdateUserCommand and RemoveUserCommand). All works fine if the buttons linked to those commands are placed outside of the DataTemplate of the control which is presenting the items. <ItemsControl ItemsSource="{Binding Users, Mode=TwoWay}" HorizontalContentAlignment="Stretch"> <ItemsControl.ItemTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="0.2*"/> <ColumnDefinition Width="0.2*"/> <ColumnDefinition Width="0.2*"/> <ColumnDefinition Width="0.2*"/> <ColumnDefinition Width="0.2*"/> </Grid.ColumnDefinitions> <TextBlock Grid.Column="0" Text="{Binding UserName}"/> <PasswordBox Grid.Column="1" Password="{Binding UserPass}"/> <TextBox Grid.Column="2" Text="{Binding UserTypeId}"/> <Button Grid.Column="3" Content="Update" cal:Click.Command="{Binding UpdateUserCommand}" cal:Click.CommandParameter="{Binding}"/> <Button Grid.Column="4" Content="Remove" cal:Click.Command="{Binding RemoveUserCommand}" cal:Click.CommandParameter="{Binding}"/> </Grid> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> What I'm trying to achieve, is : Have each row - generated by the ListView/ItemsControl - contain buttons to manage the item represented that particular row. During the runtime, the VS's output panel generated the following messages for each listbox element System.Windows.Data Error: BindingExpression path error: 'UpdateUserCommand' property not found on 'ModuleAdmin.Services.User' 'ModuleAdmin.Services.User' (HashCode=35912612). BindingExpression: Path='UpdateUserCommand' DataItem='ModuleAdmin.Services.User' (HashCode=35912612); target element is 'System.Windows.Controls.Button' (Name=''); target property is 'Command' (type 'System.Windows.Input.ICommand').. System.Windows.Data Error: BindingExpression path error: 'RemoveUserCommand' property not found on 'ModuleAdmin.Services.User' 'ModuleAdmin.Services.User' (HashCode=35912612). BindingExpression: Path='RemoveUserCommand' DataItem='ModuleAdmin.Services.User' (HashCode=35912612); target element is 'System.Windows.Controls.Button' (Name=''); target property is 'Command' (type 'System.Windows.Input.ICommand').. Which would imply that there are binding errors present. Is there any way to make this right? or is this not the way?

    Read the article

  • Problem with navigateurl in silverlight to a UNC path

    - by Aggelos Mpimpoudis
    Hi, I have a problem with a command button (implementing the ICommand). I want, when pressing the specified button to redirect the user at new tab targeting a UNC path. HtmlPage.Window.Navigate(new Uri(@"\\host\filename"), "_blank"); The problem is that browser redirects the user to the following target, besides of my intention: http://www.hostnameoftheslapplication.com/\\host\filename How can I achieve the correct navigation; Thank you in advance.

    Read the article

  • Trouble binding command in grid menu item.

    - by Pete
    I have a grid that's inside a usercontrol derived class called MediatedUserControl. I'm adding a context menu to let the user delete an item, but I've been unable to figure out how to bind the command to my command property. I'm using MVVM and my viewmodel implements a public ICommand property called DeleteSelectedItemCommand. However, when the view is displayed, I get the following message in the output window: System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='BRO.View.MediatedUserControl', AncestorLevel='1''. BindingExpression:Path=DataContext.DeleteSelectedItemCommand; DataItem=null; target element is 'BarButtonItem' (HashCode=6860584); target property is 'Command' (type 'ICommand') I feel like I generally have a good handle on bindings like this and can't figure out what it is I'm missing here. Thanks for any help you can provide. <dxg:GridControl HorizontalAlignment="Left" Margin="12,88,0,0" x:Name="gridControl1" VerticalAlignment="Top" Height="500" Width="517" DataSource="{Binding ItemList}" BorderBrush="{StaticResource {x:Static SystemColors.ActiveBorderBrushKey}}" ShowBorder="True" Background="{StaticResource {x:Static SystemColors.ControlLightBrushKey}}" UseLayoutRounding="False" DataContext="{Binding}"> <dxg:GridControl.Columns> <dxg:GridColumn FieldName="Code" Header="Code" Width="107" /> <dxg:GridColumn FieldName="Name" Header="Item" Width="173" /> <dxg:GridColumn FieldName="PricePerItem" Header="Unit Price" Width="70"> <dxg:GridColumn.EditSettings> <dxe:TextEditSettings DisplayFormat="N2" /> </dxg:GridColumn.EditSettings> </dxg:GridColumn> <dxg:GridColumn FieldName="Quantity" Header="Qty" Width="50" AllowEditing="True" /> <dxg:GridColumn FieldName="TotalPrice" Header="Total Price" Width="90"> <dxg:GridColumn.EditSettings> <dxe:TextEditSettings DisplayFormat="N2" /> </dxg:GridColumn.EditSettings> </dxg:GridColumn> </dxg:GridControl.Columns> <dxg:GridControl.View> <dxg:TableView ShowIndicator="False" ShowGroupPanel="False" MultiSelectMode="Row" AllowColumnFiltering="False" AllowBestFit="False" AllowFilterEditor="False" AllowEditing="False" AllowGrouping="False" AllowSorting="False" AllowResizing="False" AllowMoving="False" AllowMoveColumnToDropArea="False" AllowDateTimeGroupIntervalMenu="False" > <dxg:TableView.RowCellMenuCustomizations> <dxb:BarButtonItem Name="deleteRowItem" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=view:MediatedUserControl, AncestorLevel=1}, Path=DataContext.DeleteSelectedItemCommand}"> </dxb:BarButtonItem> </dxg:TableView.RowCellMenuCustomizations> </dxg:TableView> </dxg:GridControl.View>

    Read the article

  • WPF: Copy Property to Clipboard

    - by Phil Sandler
    I have a string property in my ViewModel/Datacontext and want a simple button that copies its contents to the clipboard. Is this possible to do from XAML, or I do I need to handle the button click event (or use an ICommand) to accomplish this? I thought the following would work, but my button is always greyed out: <Button Width="100" Content="Copy" Command="ApplicationCommands.Copy" CommandTarget="{Binding MyStringProperty}"/>

    Read the article

  • Bind event in custom WPF control to command in ViewModel

    - by Jon Archway
    Hi, I have a custom control that has an event. I have a window using that custom control. The window is bound to a viewmodel. I would like to have the event from the custom control direct to an ICommand on my viewmodel. I am obviously being dense here as I can't figure out how to do this. Any assistance is most welcome. Thanks

    Read the article

  • Silverlight Cream for November 21, 2011 -- #1171

    - by Dave Campbell
    In this Issue: Colin Eberhardt, Sumit Dutta, Morten Nielsen, Jesse Liberty, Jeff Blankenburg(-2-), Brian Noyes, and Tony Champion. Above the Fold: Silverlight: "PV Basics : Client-side Collections" Tony Champion WP7: "Pushpin Clustering with the Windows Phone 7 Bing Map control" Colin Eberhardt Shoutouts: Michael Palermo's latest Desert Mountain Developers is up Michael Washington's latest Visual Studio #LightSwitch Daily is up From SilverlightCream.com: Pushpin Clustering with the Windows Phone 7 Bing Map control Colin Eberhardt is back discussing Pushpins for a BingMaps app on WP7 and provides a utility class that clusters pushpins, allowing you to render 1000s of pins on an app ... all the explanation and all the code Part 22 - Windows Phone 7 - Tile Push Notification Part 22 in Sumit Dutta's WP7 series is about Tile Push Notification... nice tutorial with all the code listed Correctly displaying your current location Morten Nielsen demonstrates formatting the information from the GPS on your WP7 into something intelligible and useful Spiking the Pomodoro Timer Jesse Liberty put up a quick and dirty version of a Pomodoro timer for WP7.1 to explore the technical challenges of the Full Stack Phase 2 he's cranking up 31 Days of Mango | Day #11: Network Jeff Blankenburg's Number 10 in his 31 Days quest of WP7.1 is about the NetworkInformation namespace which gives you all sorts of info on the user's device network connection availability, type, etc. 31 Days of Mango | Day #11: Live Tiles Jeff Blankenburg takes off on Live Tiles for Day 11... big topic for a 1 day post, but he takes off on it... updating and Live Tiles too Working with Prism 4 Part 2: MVVM Basics and Commands Brian Noyes has part 2 of his Prism/MVVM series up at SilverlightShow... very nice tutorial on the basics of getting a view and viewmodel up, and setting up an ICommand to launch an Edit View... plus the code to peruse. PV Basics : Client-side Collections Tony Champion is startig a series on Silverlight 5 and Pivot Viewer... First up is some basics in dealing with the control in SL5 and talking about Client-side Collections... great informative tutorial and all the code Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    Windows Phone MIX10

    Read the article

  • How do you mock ViewModel Commands using moq?

    - by devnet247
    Hi I might be approaching this all wrong.But please help me to understand. I really want to TDD building wpf application using Moq. I would like to mock the viewmodel. Application Show a list of contacts and when you double click on a contact it shows the contact. Test Moq GetContactsCommand.Test it has been called. Test that you get a list of contacts. Not sure how to mock the viewModel and it's commands can you correct me? So I have started to do the following [Test] public void Should_be_able_to_mock_getContactsCommand_and_get_a_list_of_contacts() { //Arrange var expectedContacts = new ObservableCollection<ContactViewModel> { new ContactViewModel(new ContactModel { FirstName = "Jo", LastName = "Bloggs", Email = "[email protected]" }), new ContactViewModel(new ContactModel { FirstName = "Mary", LastName = "Bloggs", Email = "[email protected]" }) }; var mock = new Mock<IContactListViewModel>(); mock.SetupGet(x => x.GetContactsCommand).Verifiable(); mock.SetupGet(x => x.Contacts).Returns(expectedContacts); //Act //? //assert mock.VerifySet(x => x.Contacts, Times.AtLeastOnce()); mock.Object.Contacts.Count.ShouldEqual(expectedContacts.Count); } public interface IContactListViewModel { ObservableCollection<ContactViewModel> Contacts { get; set; } ICommand GetContactsCommand{ get; } } public interface IContactModel { string FirstName { get; set; } string LastName { get; set; } string Email { get; set; } } public class ContactModel : IContactModel { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } } public class ContactViewModel : ViewModelBase { private readonly ContactModel _contactModel; public ContactViewModel(ContactModel contactModel) { _contactModel = contactModel; } public string FirstName { get { return _contactModel.FirstName; } set { _contactModel.FirstName = value; OnPropertyChanged("FirstName"); } } public string LastName { get { return _contactModel.LastName; } set { _contactModel.LastName = value; OnPropertyChanged("LastName"); } } public string Email { get { return _contactModel.Emai; } set { _contactModel.Email = value; OnPropertyChanged("Email"); } } } public class ContactListViewModel : ViewModelBase, IContactListViewModel { private ObservableCollection<ContactViewModel> _contacts; public ObservableCollection<ContactViewModel> Contacts { get { return _contacts; } set { _contacts = value; OnPropertyChanged("Contacts"); } } private RelayCommand _getContactsCommand; public ICommand GetContactsCommand { get { return _getContactsCommand ?? (_getContactsCommand = new RelayCommand(x => GetContacts(), x => CanGetContacts)); } } private static bool CanGetContacts { get { return true; } } private void GetContacts() { //pretend we are going to the service or db whatever Contacts = new ObservableCollection<ContactViewModel> { new ContactViewModel(new ContactModel { FirstName = "Jo", LastName = "Bloggs", Email = "[email protected]" }), new ContactViewModel(new ContactModel { FirstName = "Mary", LastName = "Bloggs", Email = "[email protected]" }) }; } }

    Read the article

  • SelectionChanged event binding in Silverlight+MVVM-Light

    - by Budda
    The handler of the "SelectionChanged" event of the ComboBox control has the following signature: void SelectionChangedMethod(object sender, SelectionChangedEventArgs e) How to bind to that property under Silverlight 4 and MVVM-Light to the corresponding method of the ViewModel object? As far as I know, I need to do something like this: public void Changed(Object obj, SelectionChangedEventArgs e) { // .... implement logic here } RelayCommand<Object, SelectionChangedEventArgs> _command; public ICommand ObjectSelectionChanged { get { if (_command == null) { _command = new RelayCommand<Object, SelectionChangedEventArgs>(Changed); } return _command; } } The problem is that RelayCommand class in the MVVM-Light framework doesn't support 2 generic parameters... Is there any solution or workaround for this case? How bind control event to the method with 2 parameters?

    Read the article

  • Add a delay to OnContactDown events for Surface controls

    - by RTigger
    We're using the Controls.PreviewContactDown, PreviewContactUp, and PreviewContactChanged events to capture tagged items being placed, removed, and moved on the Surface, which works great in the Simulator application that comes with the surface. On an actual Surface if you moved a tagged item too quickly the cameras actually lose focus of the tag, assume it was removed, and then re-capture it when it stops moving. That provides a pretty poor experience for our clients. What I'm proposing is a way to override or create a new event that would respond to tagged item events, but not fire the event handler until after a delay... i.e. if "ContactUp" is fired, wait 100ms and THEN execute the event handler. Ideally we'd just be able to use an alternate attached property to define these event handlers, i.e. <Panel local:TagDown="TagDownEventHandler" /> And if we could get it to use ICommand objects instead of event handlers that'd be even better.

    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 Can I Add a New Command to a Control's Event

    - by Chris
    Hi, thanks for taking a look at this question. I have been building an application (VB/WPF) following Josh Smith's example of an MVVM pattern: Click here to view My Views have Controls which trigger a Command upon an event, such as a button click and these are bound to properties in the ViewModel. My ViewModel exposes properties of type ICommand which invoke the appropriate methods. This has worked well, until now! I now want to use a Thumb Control to allow a user to move an object within a Canvas. I don't believe that the Thumb has a Command capability 'out of the box'. A Thumb raises a 'DragDelta' event when being moved. So my question is as follows: How do I extend a Control's capability to issue a Command upon an event please? I wish to issue a new Command, let's say 'onDragDelta' so that I can bind it to a property in my ViewModel just like my Buttons. Thank you very much

    Read the article

  • Handling Dialogs in WPF with MVVM

    - by Ray Booysen
    In the MVVM pattern for WPF, handling dialogs is one of the more complex operations. As your view model does not know anything about the view, dialog communication can be interesting. I can expose an ICommand that when the view invokes it, a dialog can appear. Does anyone know of a good way to handle results from dialogs? I am speaking about windows dialogs such as MessageBox. One of the ways we did this was have an event on the viewmodel that the view would subscribe to when a dialog was required. public event EventHandler<MyDeleteArgs> RequiresDeleteDialog; This is OK, but it means that the view requires code which is something I would like to stay away from.

    Read the article

  • Slides and Code from my Silverlight MVVM Talk at DevConnections

    - by dwahlin
    I had a great time at the DevConnections conference in Las Vegas this year where Visual Studio 2010 and Silverlight 4 were launched. While at the conference I had the opportunity to give a full-day Silverlight workshop as well as 4 different talks and met a lot of people developing applications in Silverlight. I also had a chance to appear on a live broadcast of Channel 9 with John Papa, Ward Bell and Shawn Wildermuth, record a video with Rick Strahl covering jQuery versus Silverlight and record a few podcasts on Silverlight and ASP.NET MVC 2.  It was a really busy 4 days but I had a lot of fun chatting with people and hearing about different business problems they were solving with ASP.NET and/or Silverlight. Thanks to everyone who attended my sessions and took the time to ask questions and stop by to talk one-on-one. One of the talks I gave covered the Model-View-ViewModel pattern and how it can be used to build architecturally sound applications. Topics covered in the talk included: Understanding the MVVM pattern Benefits of the MVVM pattern Creating a ViewModel class Implementing INotifyPropertyChanged in a ViewModelBase class Binding a ViewModel declaratively in XAML Binding a ViewModel with code ICommand and ButtonBase commanding support in Silverlight 4 Using InvokeCommandBehavior to handle additional commanding needs Working with ViewModels and Sample Data in Blend Messaging support with EventBus classes, EventAggregator and Messenger My personal take on code in a code-beside file (I’m all in favor of it when used appropriately for message boxes, child windows, animations, etc.) One of the samples I showed in the talk was intended to teach all of the concepts mentioned above while keeping things as simple as possible.  The sample demonstrates quite a few things you can do with Silverlight and the MVVM pattern so check it out and feel free to leave feedback about things you like, things you’d do differently or anything else. MVVM is simply a pattern, not a way of life so there are many different ways to implement it. If you’re new to the subject of MVVM check out the following resources. I wish this talk would’ve been recorded (especially since my live and canned demos all worked :-)) but these resources will help get you going quickly. Getting Started with the MVVM Pattern in Silverlight Applications Model-View-ViewModel (MVVM) Explained Laurent Bugnion’s Excellent Talk at MIX10     Download sample code and slides from my DevConnections talk     For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit http://www.thewahlingroup.com.

    Read the article

  • Silverlight Cream for January 03, 2011 -- #1021

    - by Dave Campbell
    In this all-Submittal Issue: Gill Cleeren(-2-), Brian Noyes, Brian Genisio, René Schulte, and Andy Schwam(-2-). Above the Fold: Silverlight: "The INavigationContentLoader interface in Silverlight 4" Gill Cleeren WP7: "Sending Windows Phone Screenshots in an Email" René Schulte WCF RIA Services: "WCF RIA Services Part 10 - Exposing Domain Services To Other Clients" Brian Noyes Shoutouts: Want to know what it takes to be an MVP? Check out René Schulte's recap of 2010: Goodbye 2010 - Hello 2011 ... awesome, René! Rui Marinho sent me this post... it's WPF, but wow... WPF and Kinect! Kinect & WPF From SilverlightCream.com: The INavigationContentLoader interface in Silverlight 4 Gill Cleeren has a couple posts up... this first is a break-out of the INavigationContentLoader... what all can be done with it, in addition to the flow of the page load process broken out. Working with the RaiseCanExecuteChanged in MVVM Light (Silverlight) Gill Cleeren' latest post is a discussion of the Silverlight ICommand interface and Laurent Bugnion's RaiseCanExecuteChanged in MVVM Light, with example code. WCF RIA Services Part 10 - Exposing Domain Services To Other Clients Brian Noyes has Part 10 in his WCF RIA Services Tutorial series up at SilverlightShow ... with info on, for example, exposint an OData, SOAP, or REST/JSON endpoint, or how to consume them. Cross-Training in Silverlight & Flex–MVVM vs Presentation Model Brian Genisio finished the year off with this post in his on-going Silverlight/Flex seris comparing MVVM vs Presentation Model .. lots of good MVVM/ViewModel tips and code in this post. Sending Windows Phone Screenshots in an Email René Schulte is the perfect guy to be doing this... how about emailing a screenshot directly from inside an app, for instance Laurent's taking a screenshot from inside an app... too cool, Rene! Windows Phone 7 Application Development Tips Andy Schwam has a post up with tips he learned while creating his first WP7 app... lots of good tips, Gestures, Camera, ISO... check it out, could save you some time and tears :) WP7 Tip: Using the CameraCaptureTask for Windows Phone 7 Andy Schwam's most recent post is WP7 dev as well, and has a bunch of tips and code for using the camera, such as capturing an image, resizing, saving... good stuff. Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    Windows Phone MIX10

    Read the article

  • WEB203 &ndash; Jump into Silverlight!&hellip; and Become Effective Immediately with Tim Huckaby, Fou

    - by Robert Burger
    Getting ready for the good stuff. Definitely wish there were more Silverlight and WCF RIA sessions, but this is a start.  Was lucky to get a coveted power-enabled seat.  Luckily, due to my trustily slow Verizon data card, I can get these notes out amidst a total Internet outage here.  This is the second breakout session of the day, and is by far standing-room only.  I stepped out before the session started to get a cool Diet COKE and wouldn’t have gotten back in if I didn’t already have a seat. Tim says this is an intro session and that he’s been begging for intro sessions at TechEd for years and that by looking at this audience, he thinks the demand is there.  Admittedly, I didn’t know this was an intro session, or I might have gone elsewhere.  But, it was the very first Silverlight session, so I had to be here. Tim says he will be providing a very good comprehensive reference application at the end of the presentation.  He has just demoed it, and it is a full CRUD-based Sales Manager application based on…  AdventureWorks! Session Agenda What it is / How to get started Declarative Programming Layout and Controls, Events and Commands Working with Data Adding Style to Your Application   Silverlight…  “WPF Light” Why is the download 4.2MB?  Because the direct competitor is a 4.2MB download.  There is no technical reason it is not the entire framework.  It is purely to “be competitive”.   Getting Started Get all of the following downloads from www.silverlight.net/getstarted Install VS2010 or Visual Web Developer Express 2010 Install Silverlight 4 Tools for VS2010 Install Expression Blend 4 Install the Silverlight 4 Toolkit   Reference Application Features Uses MVVM pattern – a way to move data access code that would normally be inline within the UI and placing it in nice data access libraries Images loaded dynamically from the database, converting GIF to PNG because Silverlight does not support GIF. LINQ to SQL is the data access model WCF is the data provider and is using binary message encoding   Declarative Programming XAML replaces code for UI representation Attributes control Layout and Style Event handlers wired-up in XAML Declarative Data Binding   Layout Overview Content rendering flows inside of parent Fixed positioning (Canvas) is seldom used Panels are used to house content Margins and Padding over fixed size   Panels StackPanel – Arranges child elements into a single line oriented horizontally or vertically Grid – A flexible grid are that consists of rows and columns Canvas – An are where positions are specifically fixed WrapPanel (in Toolkit) – Positions child elements in sequential position left to right and top to bottom. DockPanel (in Toolkit) – Positions child controls within a dockable area   Positioning Horizontal and Vertical Alignment Margin – Separates an element from neighboring elements Padding – Enlarges the effective size of an element by a thickness   Controls Overview Not all controls created equal Silverlight, as a subset of WPF, so many WPF controls do not exist in the core Siverlight release Silverlight Toolkit continues to add controls, but are released in different quality bands Plenty of good 3rd party controls to fill the gaps Windows Phone 7 is to have 95% of controls available in Silverlight Core and Toolkit.   Events and Commands Standard .NET Events Routed Events Commands – based on the ICommand interface – logical action that can be invoked in several ways   Adding Style to Your Application Resource Dictionaries – Contains a hash table of key/value pairs.  Silverlight can only use Static Resources whereas WPF can also use Dynamic Resources Visual State Manager Silverlight 4 supports Implicit styles ResourceDictionary.MergedDictionaries combines many different file-based resources   Downloads

    Read the article

  • Workarounds for supporting MVVM in the Silverlight ContextMenu service

    - by cibrax
    As I discussed in my last post, some of the Silverlight controls does not support MVVM quite well out of the box without specific customizations. The Context Menu is another control that requires customizations for enabling data binding on the menu options. There are a few things that you might want to expose as view model for a menu item, such as the Text, the associated icon or the command that needs to be executed. That view model should look like this, public class MenuItemModel { public string Name { get; set; } public ICommand Command { get; set; } public Image Icon { get; set; } public object CommandParameter { get; set; } } This is how you can modify the built-in control to support data binding on the model above, public class CustomContextMenu : ContextMenu { protected override DependencyObject GetContainerForItemOverride() { CustomMenuItem item = new CustomMenuItem(); Binding commandBinding = new Binding("Command"); item.SetBinding(CustomMenuItem.CommandProperty, commandBinding);   Binding commandParameter = new Binding("CommandParameter"); item.SetBinding(CustomMenuItem.CommandParameterProperty, commandParameter);   return item; } }   public class CustomMenuItem : MenuItem { protected override DependencyObject GetContainerForItemOverride() { CustomMenuItem item = new CustomMenuItem();   Binding commandBinding = new Binding("Command"); item.SetBinding(CustomMenuItem.CommandProperty, commandBinding);   return item; } } The change is very similar to the one I made in the TreeView for manually data binding some of the Menu item properties to the model. Once you applied that change in the control, you can define it in your XAML like this. <toolkit:ContextMenuService.ContextMenu> <e:CustomContextMenu ItemsSource="{Binding MenuItems}"> <e:CustomContextMenu.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" > <ContentPresenter Margin="0 0 4 0" Content="{Binding Icon}" /> <TextBlock Margin="0" Text="{Binding Name, Mode=OneWay}" FontSize="12"/> </StackPanel> </DataTemplate> </e:CustomContextMenu.ItemTemplate> </e:CustomContextMenu> </toolkit:ContextMenuService.ContextMenu> The property MenuItems associated to the “ItemsSource” in the parent model just returns a list of supported options (menu items) in the context menu. this.menuItems = new MenuItemModel[] { new MenuItemModel { Name = "My Command", Command = new RelayCommand(OnCommandClick), Icon = ImageLoader.GetIcon("command.png") } }; The only problem I found so far with this approach is that the context menu service does not support a HierarchicalDataTemplate in case you want to have an hierarchy in the context menu (MenuItem –> Sub menu items), but I guess we can live without that.

    Read the article

  • Passing a parameter using RelayCommand defined in the ViewModel (from Josh Smith example)

    - by eesh
    I would like to pass a parameter defined in the XAML (View) of my application to the ViewModel class by using the RelayCommand. I followed Josh Smith's excellent article on MVVM and have implemented the following. XAML Code <Button Command="{Binding Path=ACommandWithAParameter}" CommandParameter="Orange" HorizontalAlignment="Left" Style="{DynamicResource SimpleButton}" VerticalAlignment="Top" Content="Button"/> ViewModel Code public RelayCommand _aCommandWithAParameter; /// <summary> /// Returns a command with a parameter /// </summary> public RelayCommand ACommandWithAParameter { get { if (_aCommandWithAParameter == null) { _aCommandWithAParameter = new RelayCommand( param => this.CommandWithAParameter("Apple") ); } return _aCommandWithAParameter; } } public void CommandWithAParameter(String aParameter) { String theParameter = aParameter; } #endregion I set a breakpoint in the CommandWithAParameter method and observed that aParameter was set to "Apple", and not "Orange". This seems obvious as the method CommandWithAParameter is being called with the literal String "Apple". However, looking up the execution stack, I can see that "Orange", the CommandParameter I set in the XAML is the parameter value for RelayCommand implemenation of the ICommand Execute interface method. That is the value of parameter in the method below of the execution stack is "Orange", public void Execute(object parameter) { _execute(parameter); } What I am trying to figure out is how to create the RelayCommand ACommandWithAParameter property such that it can call the CommandWithAParameter method with the CommandParameter "Orange" defined in the XAML. Is there a way to do this? Why do I want to do this? Part of "On The Fly Localization" In my particular implementation I want to create a SetLanguage RelayCommand that can be bound to multiple buttons. I would like to pass the two character language identifier ("en", "es", "ja", etc) as the CommandParameter and have that be defined for each "set language" button defined in the XAML. I want to avoid having to create a SetLanguageToXXX command for each language supporting and hard coding the two character language identifier into each RelayCommand in the ViewModel.

    Read the article

  • Using MVVM, how to pass SelectedItems of a XamDataGrid as parameter to the Command raised by the Co

    - by saddaypally
    Hi, I'm trying to pass the item on XamDataGrid on which I do a mouse right click to open a ContextMenu, which raises a Command in my ViewModel. Somehow the method that the Command calls is not reachable in debug mode. This is the snipped from the view <ig:XamDataGrid DataSource="{Binding DrdResults}" Height="700" Width="600"> <ig:XamDataGrid.ContextMenu> <ContextMenu DataContext="{Binding RelativeSource={RelativeSource Mode=Self}, Path=PlacementTarget.DataContext}" AllowDrop="True" Name="cmAudit"> <MenuItem Header="View History" Command="{Binding ViewTradeHistory}" CommandParameter="{Binding Path=SelectedItems}"> </MenuItem> </ContextMenu> </ig:XamDataGrid.ContextMenu> <ig:XamDataGrid.FieldSettings> <ig:FieldSettings AllowFixing="NearOrFar" AllowEdit="False" Width="auto" Height="auto" /> </ig:XamDataGrid.FieldSettings> </ig:XamDataGrid> My code in the corresponding ViewModel for this View is as follows public WPF.ICommand ViewTradeHistory { get { if (_viewTradeHistory == null) { _viewTradeHistory = new DelegateCommand( (object SelectedItems) = { this.OpenTradeHistory(SelectedItems); }); } return _viewTradeHistory; } } And lastly the actual method that gets called by the Command is as below private void OpenTradeHistory(object records) { DataPresenterBase.SelectedItemHolder auditRecords = (DataPresenterBase.SelectedItemHolder)records; // Do something with the auditRecords now. } I'm not sure what am I doing incorrectly here. Any help will be very much appreciated. Thanks, Shravan

    Read the article

< Previous Page | 1 2 3 4  | Next Page >