Search Results

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

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

  • WPF ICommand over a button

    - by toni
    Hi, I have implemented a custom IComand class for one of my buttons. The button is placed in a page 'MyPage.xaml' but its custom ICommand class is placed in another class, not in the MyPage code behind. Then from XAML I want to bind the button with its custom command class and then I do: MyPage.xaml: <Page ...> <Page.CommandBindings> <CommandBinding Command="RemoveAllCommand" CanExecute="CanExecute" Executed="Execute" /> </Page.CommandBindings> <Page.InputBindings> <MouseBinding Command="RemoveAllCommand" MouseAction="LeftClick" /> </Page.InputBindings> <...> <Button x:Name="MyButton" Command="RemoveAllCommand" .../> <...> </Page> and the custom command button class: // Here I derive from MyPage class because I want to access some objects from // Execute method public class RemoveAllCommand : MyPage, ICommand { public void Execute(Object parameter) { <...> } public bool CanExecute(Object parameter) { <...> } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } } My problem is how to say MyPage.xaml that Execute and CanExecute methods for the button is in another class and not the code behind where is placed the button. How to say these methods are in RemoveAllCommand Class in XAML page. Also I want to fire this command when click mouse event is produced in the button so I do an input binding, is it correct? Thanks

    Read the article

  • WPF ICommand over a button

    - by toni
    I have implemented a custom IComand class for one of my buttons. The button is placed in a page 'MyPage.xaml' but its custom ICommand class is placed in another class, not in the MyPage code behind. Then from XAML I want to bind the button with its custom command class and then I do: MyPage.xaml: <Page ...> <Page.CommandBindings> <CommandBinding Command="RemoveAllCommand" CanExecute="CanExecute" Executed="Execute" /> </Page.CommandBindings> <Page.InputBindings> <MouseBinding Command="RemoveAllCommand" MouseAction="LeftClick" /> </Page.InputBindings> <...> <Button x:Name="MyButton" Command="RemoveAllCommand" .../> <...> </Page> and the custom command button class: // Here I derive from MyPage class because I want to access some objects from // Execute method public class RemoveAllCommand : MyPage, ICommand { public void Execute(Object parameter) { <...> } public bool CanExecute(Object parameter) { <...> } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } } My problem is how to say MyPage.xaml that Execute and CanExecute methods for the button is in another class and not the code behind where is placed the button. How to say these methods are in RemoveAllCommand Class in XAML page. Also I want to fire this command when click mouse event is produced in the button so I do an input binding, is it correct? Thanks

    Read the article

  • How to use ICommand in Silverlight 4

    - by Toran Billups
    I see a great deal of information that says "yes the ICommand bits will ship with SL 4" but I can't seem to find an official post / example / etc Does anyone know if this is supported with the Silverlight 4 RTM runtime? If so do you know what namespace it can be found?

    Read the article

  • WPF: TreeViewItem bound to an ICommand

    - by Richard
    Hi All, I am busy creating my first MVVM application in WPF. Basically the problem I am having is that I have a TreeView (System.Windows.Controls.TreeView) which I have placed on my WPF Window, I have decide that I will bind to a ReadOnlyCollection of CommandViewModel items, and these items consist of a DisplayString, Tag and a RelayCommand. Now in the XAML, I have my TreeView and I have successfully bound my ReadOnlyCollection to this. I can view this and everything looks fine in the UI. The issue now is that I need to bind the RelayCommand to the Command of the TreeViewItem, however from what I can see the TreeViewItem doesn't have a Command. Does this force me to do it in the IsSelected property or even in the Code behind TreeView_SelectedItemChanged method or is there a way to do this magically in WPF? This is the code I have: <TreeView BorderBrush="{x:Null}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <TreeView.Items> <TreeViewItem Header="New Commands" ItemsSource="{Binding Commands}" DisplayMemberPath="DisplayName" IsExpanded="True"> </TreeViewItem> </TreeView.Items> and ideally I would love to just go: <TreeView BorderBrush="{x:Null}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <TreeView.Items> <TreeViewItem Header="New Trade" ItemsSource="{Binding Commands}" DisplayMemberPath="DisplayName" IsExpanded="True" Command="{Binding Path=Command}"> </TreeViewItem> </TreeView.Items> Does someone have a solution that allows me to use the RelayCommand infrastructure I have. Thanks guys, much appreciated! Richard

    Read the article

  • MVVM (ICommand) in Silverlight

    - by Andrey Khataev
    Hello! Please, don't judge strictly if this question was discussed previously or indirectly answered in huge nearby prism and mvvm blogs. In WPF implementation of RelayCommand or DelegateCommand classes there is a such eventhandler /// <summary> /// Occurs whenever the state of the application changes such that the result of a call to <see cref="CanExecute"/> may return a different value. /// </summary> public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } but in SL subset of namespaces there are no CommandManager class. And this is where I'm stuck. I haven't yet found an workaround for this in MVVM adoptation for SL (PRISM is so complex for me yet). Different simple HelloWorldMVVM apps don't deal with at all. Thanks in advance and sorry for my English -)

    Read the article

  • ICommand.CanExecute being passed null even though CommandParameter is set...

    - by chaiguy
    I have a tricky problem where I am binding a ContextMenu to a set of ICommand-derived objects, and setting the Command and CommandParameter properties on each MenuItem via a style: <ContextMenu ItemsSource="{Binding Source={x:Static OrangeNote:Note.MultiCommands}}"> <ContextMenu.Resources> <Style TargetType="MenuItem"> <Setter Property="Header" Value="{Binding Path=Title}" /> <Setter Property="Command" Value="{Binding}" /> <Setter Property="CommandParameter" Value="{Binding Source={x:Static OrangeNote:App.Screen}, Path=SelectedNotes}" /> ... However, while ICommand.Execute( object ) gets passed the set of selected notes as it should, ICommand.CanExecute( object ) (which is called when the menu is created) is getting passed null. I've checked and the selected notes collection is properly instantiated before the call is made (in fact it's assigned a value in its declaration, so it is never null). I can't figure out why CanEvaluate is getting passed null.

    Read the article

  • ICOmmand - canexecute can not disable Button with image content.

    - by Anish
    Hi , I have a button control in my wpf-mvvm application. I use an ICommand property (defined in viewmodel) to bind the button click event to viewmodel. I have - execute and canexecute parameters for my ICommand implementation (RelayCommand). Even if CanExecute is false...button is not disabled...WHEN button CONTENT is IMAGE But, when button content is text..enable/disable works fine. <Button DockPanel.Dock="Top" Command="{Binding Path=MoveUpCommand}"> <Button.Content> <Image Source="/Resources/MoveUpArrow.png"></Image> </Button.Content> <Style> <Style.Triggers> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Opacity" Value=".5" /> </Trigger> </Style.Triggers> </Style> </Button>

    Read the article

  • How to bind the Command property of the ItemTemplate CheckBox to ViewModel object's property?

    - by 123Developer
    Let me ask this question with a pseudo code: Where "Contacts" the ViewModel object set as the DataContext for the window. "Contacts" has "PersonCollection" , public ICommand PersonSelectedCommand properties. "PersonCollection" is List "Person" has Name, Age properties Currently this is not working as CheckBox is trying to find and bind the ICommand "PersonSelectedCommand" property of object "person", which does not exists! How will bind the CheckBox to the ICommand "PersonSelectedCommand" property of object "Contact" Thanks and regards 123Deveopler

    Read the article

  • How to Bind a Command in WPF

    - by MegaMind
    Sometimes we used complex ways so many times, we forgot the simplest ways to do the task. I know how to do command binding, but i always use same approach. Create a class that implements ICommand interface and from the view model i create new instance of that class and binding works like a charm. This is the code that i used for command binding public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = this; testCommand = new MeCommand(processor); } ICommand testCommand; public ICommand test { get { return testCommand; } } public void processor() { MessageBox.Show("hello world"); } } public class MeCommand : ICommand { public delegate void ExecuteMethod(); private ExecuteMethod meth; public MeCommand(ExecuteMethod exec) { meth = exec; } public bool CanExecute(object parameter) { return false; } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { meth(); } } But i want to know the basic way to do this, no third party dll no new class creation. Do this simple command binding using a single class. Actual class implements from ICommand interface and do the work.

    Read the article

  • Reuse controls inside a usercontrol

    - by Lawrence A. Contreras
    I have a UserControl UserControl1 and a button inside the UserControl1. And I have a UserControl1ViewModel that has an ICommand property for the button. Using this command I need to call a method outside(from other VMs or VM of the MainWindow) the VM. What is the best practice for this?

    Read the article

  • binding a command inside a listbox item to a property on the viewmodel parent

    - by giddy
    I've been working on this for about an hour and looked at all related SO questions. My problem is very simple: I have HomePageVieModel: HomePageVieModel +IList<NewsItem> AllNewsItems +ICommand OpenNewsItem My markup: <Window DataContext="{Binding HomePageViewModel../> <ListBox ItemsSource="{Binding Path=AllNewsItems}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock> <Hyperlink Command="{Binding Path=OpenNews}"> <TextBlock Text="{Binding Path=NewsContent}" /> </Hyperlink> </TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> The list shows fine with all the items, but for the life of me whatever I try for the Command won't work: <Hyperlink Command="{Binding Path=OpenNewsItem, RelativeSource={RelativeSource AncestorType=vm:HomePageViewModel, AncestorLevel=1}}"> <Hyperlink Command="{Binding Path=OpenNewsItem, RelativeSource={RelativeSource AncestorType=vm:HomePageViewModel,**Mode=FindAncestor}**}"> <Hyperlink Command="{Binding Path=OpenNewsItem, RelativeSource={RelativeSource AncestorType=vm:HomePageViewModel,**Mode=TemplatedParent}**}"> I just always get : System.Windows.Data Error: 4 : Cannot find source for binding with reference .....

    Read the article

  • binding a command inside a listbox item to a property on the viewmodel parent

    - by gideon
    I've been working on this for about an hour and looked at all related SO questions. My problem is very simple: I have HomePageVieModel: HomePageVieModel +IList<NewsItem> AllNewsItems +ICommand OpenNews My markup: <Window DataContext="{Binding HomePageViewModel../> <ListBox ItemsSource="{Binding Path=AllNewsItems}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock> <Hyperlink Command="{Binding Path=OpenNews}"> <TextBlock Text="{Binding Path=NewsContent}" /> </Hyperlink> </TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> The list shows fine with all the items, but for the life of me whatever I try for the Command won't work: <Hyperlink Command="{Binding Path=OpenNewsItem, RelativeSource={RelativeSource AncestorType=vm:HomePageViewModel, AncestorLevel=1}}"> <Hyperlink Command="{Binding Path=OpenNewsItem, RelativeSource={RelativeSource AncestorType=vm:HomePageViewModel,**Mode=FindAncestor}**}"> <Hyperlink Command="{Binding Path=OpenNewsItem, RelativeSource={RelativeSource AncestorType=vm:HomePageViewModel,**Mode=TemplatedParent}**}"> I just always get : System.Windows.Data Error: 4 : Cannot find source for binding with reference ..... Update I am setting my ViewModel like this? Didn't think this would matter: <Window.DataContext> <Binding Path="HomePage" Source="{StaticResource Locator}"/> </Window.DataContext> I use the ViewModelLocator class from the MVVMLight toolkit which does the magic.

    Read the article

  • Binding command to button in silverlight 4 using mvvm

    - by Archie
    Hello, I have a user control called HomePage.xaml. I'm creating a model instance (using MVVM pattern) in the code behind file in the constructor of page as MainViewModel model = new MainViewModel(); I have a button in HomePage.xaml which I want to bind to the command inside MainViewModel called GetData() and want to populate the data in datagrid. MainViewModel has an ObservableCollection which I would use to bind the data in datagrid. Populating the data in datagrid without binding command works fine. I'm binding the button as: <StackPanel x:Name="stkPanelInput" Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center"> <Button x:Name="buttonGetData" Width="70" Content="GetData" Command="{Binding GetData}" Click="buttonGetData_Click"/> </StackPanel> How shall I bind the command using MVVM? Thanks.

    Read the article

  • WPF : Command routing for Keyboard shortcuts.

    - by Sprotty
    Basically I want to create a keyboard shortcut which is valid within the scope of a window, and not just enabled when focus is within the control that binds it. in more detail.... I have a window which has 3 controls a toolbar textbox Custom Control The toolbar has a button bound to the Command CustomCommands.CmdA and linked to 'Ctrl-T'. My Custom Control can process CmdA. When I run the app and click on my custom control CmdA is enabled and works fine. Also Ctrl-T cause the command to fire. However when I select the text box, my custom command CmdA becomes disabled. I can rectify this by setting the command target for CmdA's button. Now when I select the textBox, CmdA is still enabled. But the Keyboard shortcut Ctrl-T does nothing. Is there any easy way to change the scope of keyboard shortcuts? Or do I need to catch the keypress somewhere lower down, and work out which Command it relates to and route it myself (if so is there a framework within which to do this?) Many Thanks Simon

    Read the article

  • Subscribe to the Button's events into a custom control

    - by ThitoO
    Do you know how can I subscribe to an event of the base of my customControl ? I've a custom control with some dependency properties : public class MyCustomControl : Button { static MyCustomControl () { DefaultStyleKeyProperty.OverrideMetadata( typeof( MyCustomControl ), new FrameworkPropertyMetadata( typeof( MyCustomControl ) ) ); } public ICommand KeyDownCommand { get { return (ICommand)GetValue( KeyDownCommandProperty ); } set { SetValue( KeyDownCommandProperty, value ); } } public static readonly DependencyProperty KeyDownCommandProperty = DependencyProperty.Register( "KeyDownCommand", typeof( ICommand ), typeof( MyCustomControl ) ); public ICommand KeyUpCommand { get { return (ICommand)GetValue( KeyUpCommandProperty ); } set { SetValue( KeyUpCommandProperty, value ); } } public static readonly DependencyProperty KeyUpCommandProperty = DependencyProperty.Register( "KeyUpCommand", typeof( ICommand ), typeof( MyCustomControl ) ); public ICommand KeyPressedCommand { get { return (ICommand)GetValue( KeyPressedCommandProperty ); } set { SetValue( KeyPressedCommandProperty, value ); } } public static readonly DependencyProperty KeyPressedCommandProperty = DependencyProperty.Register( "KeyPressedCommand", typeof( ICommand ), typeof( MyCustomControl ) ); } And I whant to subscribe to Button's events (like MouseLeftButtonDown) to run some code in my customControl. Do you know how can I do something like this in the constructor ? static MyCustomControl() { DefaultStyleKeyProperty.OverrideMetadata( typeof( MyCustomControl ), new FrameworkPropertyMetadata( typeof( MyCustomControl ) ) ); MouseLeftButtonDownEvent += (object sender, MouseButtonEventArgs e) => "something"; } Thanks for you help

    Read the article

  • Should I use ICommand or Expression.Interactions InvokeCommand for MVVM in Silverlight 4?

    - by phejndorf
    I'm about to embark on a new project in Silverlight 4, and definitely want to take advantage of the MVVM pattern, now I've finally grasped the basics. For implementing commands in Silverlight 4 it seems there are rather a lot of options ranging from the new built-in Command/ICommand option on the Button, over the InvokeCommand defined in the Microsoft.Expressions.Interactivity namespace and on to the range of assisting MVVM frameworks (Prism, MVVMlight etc). Does anyone here have gotcha's, experience and wisdom to share on this subject?

    Read the article

  • How to design a scriptable communication emulator?

    - by Hawk
    Requirement: We need a tool that simulates a hardware device that communicates via RS232 or TCP/IP to allow us to test our main application which will communicate with the device. Current flow: User loads script Parse script into commands User runs script Execute commands Script / commands (simplified for discussion): Connect RS232 = RS232ConnectCommand Connect TCP/IP = TcpIpConnectCommand Send data = SendCommand Receive data = ReceiveCommand Disconnect = DisconnectCommand All commands implement the ICommand interface. The command runner simply executes a sequence of ICommand implementations sequentially thus ICommand must have an Execute exposure, pseudo code: void Execute(ICommunicator context) The Execute method takes a context argument which allows the command implementations to execute what they need to do. For instance SendCommand will call context.Send, etc. The problem RS232ConnectCommand and TcpIpConnectCommand needs to instantiate the context to be used by subsequent commands. How do you handle this elegantly? Solution 1: Change ICommand Execute method to: ICommunicator Execute(ICommunicator context) While it will work it seems like a code smell. All commands now need to return the context which for all commands except the connection ones will be the same context that is passed in. Solution 2: Create an ICommunicatorWrapper (ICommunicationBroker?) which follows the decorator pattern and decorates ICommunicator. It introduces a new exposure: void SetCommunicator(ICommunicator communicator) And ICommand is changed to use the wrapper: void Execute(ICommunicationWrapper context) Seems like a cleaner solution. Question Is this a good design? Am I on the right track?

    Read the article

  • Silverlight Commands Hacks: Passing EventArgs as CommandParameter to DelegateCommand triggered by Ev

    - by brainbox
    Today I've tried to find a way how to pass EventArgs as CommandParameter to DelegateCommand triggered by EventTrigger. By reverse engineering of default InvokeCommandAction I find that blend team just ignores event args.To resolve this issue I have created my own action for triggering delegate commands.public sealed class InvokeDelegateCommandAction : TriggerAction<DependencyObject>{    /// <summary>    ///     /// </summary>    public static readonly DependencyProperty CommandParameterProperty =        DependencyProperty.Register("CommandParameter", typeof(object), typeof(InvokeDelegateCommandAction), null);    /// <summary>    ///     /// </summary>    public static readonly DependencyProperty CommandProperty = DependencyProperty.Register(        "Command", typeof(ICommand), typeof(InvokeDelegateCommandAction), null);    /// <summary>    ///     /// </summary>    public static readonly DependencyProperty InvokeParameterProperty = DependencyProperty.Register(        "InvokeParameter", typeof(object), typeof(InvokeDelegateCommandAction), null);    private string commandName;    /// <summary>    ///     /// </summary>    public object InvokeParameter    {        get        {            return this.GetValue(InvokeParameterProperty);        }        set        {            this.SetValue(InvokeParameterProperty, value);        }    }    /// <summary>    ///     /// </summary>    public ICommand Command    {        get        {            return (ICommand)this.GetValue(CommandProperty);        }        set        {            this.SetValue(CommandProperty, value);        }    }    /// <summary>    ///     /// </summary>    public string CommandName    {        get        {            return this.commandName;        }        set        {            if (this.CommandName != value)            {                this.commandName = value;            }        }    }    /// <summary>    ///     /// </summary>    public object CommandParameter    {        get        {            return this.GetValue(CommandParameterProperty);        }        set        {            this.SetValue(CommandParameterProperty, value);        }    }    /// <summary>    ///     /// </summary>    /// <param name="parameter"></param>    protected override void Invoke(object parameter)    {        this.InvokeParameter = parameter;                if (this.AssociatedObject != null)        {            ICommand command = this.ResolveCommand();            if ((command != null) && command.CanExecute(this.CommandParameter))            {                command.Execute(this.CommandParameter);            }        }    }    private ICommand ResolveCommand()    {        ICommand command = null;        if (this.Command != null)        {            return this.Command;        }        var frameworkElement = this.AssociatedObject as FrameworkElement;        if (frameworkElement != null)        {            object dataContext = frameworkElement.DataContext;            if (dataContext != null)            {                PropertyInfo commandPropertyInfo = dataContext                    .GetType()                    .GetProperties(BindingFlags.Public | BindingFlags.Instance)                    .FirstOrDefault(                        p =>                        typeof(ICommand).IsAssignableFrom(p.PropertyType) &&                        string.Equals(p.Name, this.CommandName, StringComparison.Ordinal)                    );                if (commandPropertyInfo != null)                {                    command = (ICommand)commandPropertyInfo.GetValue(dataContext, null);                }            }        }        return command;    }}Example:<ComboBox>    <ComboBoxItem Content="Foo option 1" />    <ComboBoxItem Content="Foo option 2" />    <ComboBoxItem Content="Foo option 3" />    <Interactivity:Interaction.Triggers>        <Interactivity:EventTrigger EventName="SelectionChanged" >            <Presentation:InvokeDelegateCommandAction                 Command="{Binding SubmitFormCommand}"                CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=InvokeParameter}" />        </Interactivity:EventTrigger>    </Interactivity:Interaction.Triggers>                </ComboBox>BTW: InvokeCommanAction CommandName property are trying to find command in properties of view. It very strange, because in MVVM pattern command should be in viewmodel supplied to datacontext.

    Read the article

  • Wpf user control button command is not firing in viewmodel

    - by mani1985
    hi, i have a user control in which there is a button. i wrote icommand in the viewmodel for the button to call some function. when i use this user control in some other page ,the user control button click is not working. my xaml Save my view model private ICommand _insertNewNote; public ICommand InsertNewNote { get { if (_insertNewNote == null) { _insertNewNote = new RelayCommand( param = this.InsertNewExceptionNote()); } return _insertNewNote; } } public void InsertNewExceptionNote() { //... } my problem is when i use this user control in some page like this the user control is getting displayed in the page. but the button in the user control is not firing when i click it. user control view model icommand is not at all initialized. please provide me a solution. Thanks in advance.

    Read the article

  • Maintaining State in Mud Engine

    - by Johnathon Sullinger
    I am currently working on a Mud Engine and have started implementing my state engine. One of the things that has me troubled is maintaining different states at once. For instance, lets say that the user has started a tutorial, which requires specific input. If the user types "help" I want to switch in to a help state, so they can get the help they need, then return them to the original state once exiting the help. my state system uses a State Manager to manage the state per user: public class StateManager { /// <summary> /// Gets the current state. /// </summary> public IState CurrentState { get; private set; } /// <summary> /// Gets the states available for use. /// </summary> /// <value> public List<IState> States { get; private set; } /// <summary> /// Gets the commands available. /// </summary> public List<ICommand> Commands { get; private set; } /// <summary> /// Gets the mob that this manager controls the state of. /// </summary> public IMob Mob { get; private set; } public void Initialize(IMob mob, IState initialState = null) { this.Mob = mob; if (initialState != null) { this.SwitchState(initialState); } } /// <summary> /// Performs the command. /// </summary> /// <param name="message">The message.</param> public void PerformCommand(IMessage message) { if (this.CurrentState != null) { ICommand command = this.CurrentState.GetCommand(message); if (command is NoOpCommand) { // NoOperation commands indicate that the current state is not finished yet. this.CurrentState.Render(this.Mob); } else if (command != null) { command.Execute(this.Mob); } else if (command == null) { new InvalidCommand().Execute(this.Mob); } } } /// <summary> /// Switches the state. /// </summary> /// <param name="state">The state.</param> public void SwitchState(IState state) { if (this.CurrentState != null) { this.CurrentState.Cleanup(); } this.CurrentState = state; if (state != null) { this.CurrentState.Render(this.Mob); } } } Each of the different states that the user can be in, is a Type implementing IState. public interface IState { /// <summary> /// Renders the current state to the players terminal. /// </summary> /// <param name="player">The player to render to</param> void Render(IMob mob); /// <summary> /// Gets the Command that the player entered and preps it for execution. /// </summary> /// <returns></returns> ICommand GetCommand(IMessage command); /// <summary> /// Cleanups this instance during a state change. /// </summary> void Cleanup(); } Example state: public class ConnectState : IState { /// <summary> /// The connected player /// </summary> private IMob connectedPlayer; public void Render(IMob mob) { if (!(mob is IPlayer)) { throw new NullReferenceException("ConnectState can only be used with a player object implementing IPlayer"); } //Store a reference for the GetCommand() method to use. this.connectedPlayer = mob as IPlayer; var server = mob.Game as IServer; var game = mob.Game as IGame; // It is not guaranteed that mob.Game will implement IServer. We are only guaranteed that it will implement IGame. if (server == null) { throw new NullReferenceException("LoginState can only be set to a player object that is part of a server."); } //Output the game information mob.Send(new InformationalMessage(game.Name)); mob.Send(new InformationalMessage(game.Description)); mob.Send(new InformationalMessage(string.Empty)); //blank line //Output the server MOTD information mob.Send(new InformationalMessage(string.Join("\n", server.MessageOfTheDay))); mob.Send(new InformationalMessage(string.Empty)); //blank line mob.StateManager.SwitchState(new LoginState()); } /// <summary> /// Gets the command. /// </summary> /// <param name="message">The message.</param> /// <returns>Returns no operation required.</returns> public Commands.ICommand GetCommand(IMessage message) { return new NoOpCommand(); } /// <summary> /// Cleanups this instance during a state change. /// </summary> public void Cleanup() { // We have nothing to clean up. return; } } With the way that I have my FSM set up at the moment, the user can only ever have one state at a time. I read a few different posts on here about state management but nothing regarding keeping a stack history. I thought about using a Stack collection, and just pushing new states on to the stack then popping them off as the user moves out from one. It seems like it would work, but I'm not sure if it is the best approach to take. I'm looking for recommendations on this. I'm currently swapping state from within the individual states themselves as well which I'm on the fence about if it makes sense to do there or not. The user enters a command, the StateManager passes the command to the current State and lets it determine if it needs it (like passing in a password after entering a user name), if the state doesn't need any further commands, it returns null. If it does need to continue doing work, it returns a No Operation to let the state manager know that the state still requires further input from the user. If null is returned, the state manager will then go find the appropriate state for the command entered by the user. Example state requiring additional input from the user public class LoginState : IState { /// <summary> /// The connected player /// </summary> private IPlayer connectedPlayer; private enum CurrentState { FetchUserName, FetchPassword, InvalidUser, } private CurrentState currentState; /// <summary> /// Renders the current state to the players terminal. /// </summary> /// <param name="mob"></param> /// <exception cref="System.NullReferenceException"> /// ConnectState can only be used with a player object implementing IPlayer /// or /// LoginState can only be set to a player object that is part of a server. /// </exception> public void Render(IMob mob) { if (!(mob is IPlayer)) { throw new NullReferenceException("ConnectState can only be used with a player object implementing IPlayer"); } //Store a reference for the GetCommand() method to use. this.connectedPlayer = mob as IPlayer; var server = mob.Game as IServer; // Register to receive new input from the user. mob.ReceivedMessage += connectedPlayer_ReceivedMessage; if (server == null) { throw new NullReferenceException("LoginState can only be set to a player object that is part of a server."); } this.currentState = CurrentState.FetchUserName; switch (this.currentState) { case CurrentState.FetchUserName: mob.Send(new InputMessage("Please enter your user name")); break; case CurrentState.FetchPassword: mob.Send(new InputMessage("Please enter your password")); break; case CurrentState.InvalidUser: mob.Send(new InformationalMessage("Invalid username/password specified.")); this.currentState = CurrentState.FetchUserName; mob.Send(new InputMessage("Please enter your user name")); break; } } /// <summary> /// Receives the players input. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> void connectedPlayer_ReceivedMessage(object sender, IMessage e) { // Be good memory citizens and clean ourself up after receiving a message. // Not doing this results in duplicate events being registered and memory leaks. this.connectedPlayer.ReceivedMessage -= connectedPlayer_ReceivedMessage; ICommand command = this.GetCommand(e); } /// <summary> /// Gets the Command that the player entered and preps it for execution. /// </summary> /// <param name="command"></param> /// <returns>Returns the ICommand specified.</returns> public Commands.ICommand GetCommand(IMessage command) { if (this.currentState == CurrentState.FetchUserName) { this.connectedPlayer.Name = command.Message; this.currentState = CurrentState.FetchPassword; } else if (this.currentState == CurrentState.FetchPassword) { // find user } return new NoOpCommand(); } /// <summary> /// Cleanups this instance during a state change. /// </summary> public void Cleanup() { // If we have a player instance, we clean up the registered event. if (this.connectedPlayer != null) { this.connectedPlayer.ReceivedMessage -= this.connectedPlayer_ReceivedMessage; } } Maybe my entire FSM isn't wired up in the best way, but I would appreciate input on what would be the best to maintain a stack of state in a MUD game engine, and if my states should be allowed to receive the input from the user or not to check what command was entered before allowing the state manager to switch states. Thanks in advance.

    Read the article

  • What's the best way to expose a Model object in a ViewModel?

    - by Angel
    In a WPF MVVM application, I exposed my model object into my viewModel by creating an instance of Model class (which cause dependency) into ViewModel. Instead of creating separate VM properties, I wrap the Model properties inside my ViewModel Property. My model is just an entity framework generated proxy class: public partial class TblProduct { public TblProduct() { this.TblPurchaseDetails = new HashSet<TblPurchaseDetail>(); this.TblPurchaseOrderDetails = new HashSet<TblPurchaseOrderDetail>(); this.TblSalesInvoiceDetails = new HashSet<TblSalesInvoiceDetail>(); this.TblSalesOrderDetails = new HashSet<TblSalesOrderDetail>(); } public int ProductId { get; set; } public string ProductCode { get; set; } public string ProductName { get; set; } public int CategoryId { get; set; } public string Color { get; set; } public Nullable<decimal> PurchaseRate { get; set; } public Nullable<decimal> SalesRate { get; set; } public string ImagePath { get; set; } public bool IsActive { get; set; } public virtual TblCompany TblCompany { get; set; } public virtual TblProductCategory TblProductCategory { get; set; } public virtual TblUser TblUser { get; set; } public virtual ICollection<TblPurchaseDetail> TblPurchaseDetails { get; set; } public virtual ICollection<TblPurchaseOrderDetail> TblPurchaseOrderDetails { get; set; } public virtual ICollection<TblSalesInvoiceDetail> TblSalesInvoiceDetails { get; set; } public virtual ICollection<TblSalesOrderDetail> TblSalesOrderDetails { get; set; } } Here is my ViewModel: public class ProductViewModel : WorkspaceViewModel { #region Constructor public ProductViewModel() { StartApp(); } #endregion //Constructor #region Properties private IProductDataService _dataService; public IProductDataService DataService { get { if (_dataService == null) { if (IsInDesignMode) { _dataService = new ProductDataServiceMock(); } else { _dataService = new ProductDataService(); } } return _dataService; } } //Get and set Model object private TblProduct _product; public TblProduct Product { get { return _product ?? (_product = new TblProduct()); } set { _product = value; } } #region Public Properties public int ProductId { get { return Product.ProductId; } set { if (Product.ProductId == value) { return; } Product.ProductId = value; RaisePropertyChanged("ProductId"); } } public string ProductName { get { return Product.ProductName; } set { if (Product.ProductName == value) { return; } Product.ProductName = value; RaisePropertyChanged(() => ProductName); } } private ObservableCollection<TblProduct> _productRecords; public ObservableCollection<TblProduct> ProductRecords { get { return _productRecords; } set { _productRecords = value; RaisePropertyChanged("ProductRecords"); } } //Selected Product private TblProduct _selectedProduct; public TblProduct SelectedProduct { get { return _selectedProduct; } set { _selectedProduct = value; if (_selectedProduct != null) { this.ProductId = _selectedProduct.ProductId; this.ProductCode = _selectedProduct.ProductCode; } RaisePropertyChanged("SelectedProduct"); } } #endregion //Public Properties #endregion // Properties #region Commands private ICommand _newCommand; public ICommand NewCommand { get { if (_newCommand == null) { _newCommand = new RelayCommand(() => ResetAll()); } return _newCommand; } } private ICommand _saveCommand; public ICommand SaveCommand { get { if (_saveCommand == null) { _saveCommand = new RelayCommand(() => Save()); } return _saveCommand; } } private ICommand _deleteCommand; public ICommand DeleteCommand { get { if (_deleteCommand == null) { _deleteCommand = new RelayCommand(() => Delete()); } return _deleteCommand; } } #endregion //Commands #region Methods private void StartApp() { LoadProductCollection(); } private void LoadProductCollection() { var q = DataService.GetAllProducts(); this.ProductRecords = new ObservableCollection<TblProduct>(q); } private void Save() { if (SelectedOperateMode == OperateModeEnum.OperateMode.New) { //Pass the Model object into Dataservice for save DataService.SaveProduct(this.Product); } else if (SelectedOperateMode == OperateModeEnum.OperateMode.Edit) { //Pass the Model object into Dataservice for Update DataService.UpdateProduct(this.Product); } ResetAll(); LoadProductCollection(); } #endregion //Methods } Here is my Service class: class ProductDataService:IProductDataService { /// <summary> /// Context object of Entity Framework model /// </summary> private MaizeEntities Context { get; set; } public ProductDataService() { Context = new MaizeEntities(); } public IEnumerable<TblProduct> GetAllProducts() { using(var context=new R_MaizeEntities()) { var q = from p in context.TblProducts where p.IsDel == false select p; return new ObservableCollection<TblProduct>(q); } } public void SaveProduct(TblProduct _product) { using(var context=new R_MaizeEntities()) { _product.LastModUserId = GlobalObjects.LoggedUserID; _product.LastModDttm = DateTime.Now; _product.CompanyId = GlobalObjects.CompanyID; context.TblProducts.Add(_product); context.SaveChanges(); } } public void UpdateProduct(TblProduct _product) { using (var context = new R_MaizeEntities()) { context.TblProducts.Attach(_product); context.Entry(_product).State = EntityState.Modified; _product.LastModUserId = GlobalObjects.LoggedUserID; _product.LastModDttm = DateTime.Now; _product.CompanyId = GlobalObjects.CompanyID; context.SaveChanges(); } } public void DeleteProduct(int _productId) { using (var context = new R_MaizeEntities()) { var product = (from c in context.TblProducts where c.ProductId == _productId select c).First(); product.LastModUserId = GlobalObjects.LoggedUserID; product.LastModDttm = DateTime.Now; product.IsDel = true; context.SaveChanges(); } } } I exposed my model object in my viewModel by creating an instance of it using new keyword, also I instantiated my DataService class in VM. I know this will cause a strong dependency. So: What's the best way to expose a Model object in a ViewModel? What's the best way to use DataService in VM?

    Read the article

1 2 3 4  | Next Page >