Search Results

Search found 4517 results on 181 pages for 'mvvm light'.

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

  • Using Unit of Work design pattern / NHibernate Sessions in an MVVM WPF

    - by Echiban
    I think I am stuck in the paralysis of analysis. Please help! I currently have a project that Uses NHibernate on SQLite Implements Repository and Unit of Work pattern: http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/04/10/nhibernate-and-the-unit-of-work-pattern.aspx MVVM strategy in a WPF app Unit of Work implementation in my case supports one NHibernate session at a time. I thought at the time that this makes sense; it hides inner workings of NHibernate session from ViewModel. Now, according to Oren Eini (Ayende): http://msdn.microsoft.com/en-us/magazine/ee819139.aspx He convinces the audience that NHibernate sessions should be created / disposed when the view associated with the presenter / viewmodel is disposed. He presents issues why you don't want one session per windows app, nor do you want a session to be created / disposed per transaction. This unfortunately poses a problem because my UI can easily have 10+ view/viewmodels present in an app. He is presenting using a MVP strategy, but does his advice translate to MVVM? Does this mean that I should scrap the unit of work and have viewmodel create NHibernate sessions directly? Should a WPF app only have one working session at a time? If that is true, when should I create / dispose a NHibernate session? And I still haven't considered how NHibernate Stateless sessions fit into all this! My brain is going to explode. Please help!

    Read the article

  • ListView + MultipleSelect + MVVM = ?

    - by Dave
    If I were to say "the heck with it!", I could just give my ListView with SelectionMode="Multiple" a name, and be able to get all of the selected items very easily. But I'm trying to stick to MVVM as much as possible, and I want to somehow databind to an ObservableCollection that holds the value from the Name column for each selected item. How in the world do you do this? Single selection is simple, but the multi selection solution is not obvious to me with my current WPF / MVVM knowledge. I read this question on SO, and while it does give me some good insight, I don't know how to add the necessary binding to a row, because I am using a ListView with a GridView as its View, not a ListBox. Here's what my XAML basically looks like: <ListView DockPanel.Dock="Top" ItemsSource="{Binding ClientPreview}" SelectionMode="Multiple"> <ListView.View> <GridView AllowsColumnReorder="False"> <GridViewColumn Header="Name"> <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Path=Name}" /> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn Header="Address"> <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Path=Address}" /> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> </GridView> </ListView.View> </ListView> It sounds like the right thing to do is to databind each row's IsSelected property to each object stored in the ObservableCollection I'm databinding to. I just haven't figured out how to do this.

    Read the article

  • FxCop hates my usage of MVVM

    - by Dave
    I've just started to work with FxCop to see how poorly my code does against its full set of rules. I'm starting off with the "Breaking" rules, and the first one I came across was CA2227, which basically says that you should make a collection property's setter readonly, so that you can't accidentally change the collection data. Since I'm using MVVM, I've found it very convenient to use an ObservableCollection with get/set properties because it makes my GUI updates easy and concise in the code-behind. However, I can also see what FxCop is complaining about. Another situation that I just ran into is with WF, where I need to set the parameters when creating the workflow, and I'd hate to have to write a wrapper class around the collection I'm using just to avoid this particular error message. For example, here's a sample runtime error message that I get when I make properties readonly: The activity 'MyWorkflow' has no public writable property named 'MyCollectionOfStuff' What are you opinions on this? I could either ignore this particular error, but that's probably not good because I could conceivably violate this rule elsewhere in the code where MVVM doesn't apply (model only code, for example). I think I could also change it from a property to a class with methods to manipulate the underlying collection, and then raise the necessary notification from the setter method. I'm a little confused... can anyone shed some light on this?

    Read the article

  • WPF MVVM Chart change axes

    - by c0uchm0nster
    I'm new to WPF and MVVM. I'm struggling to determine the best way to change the view of a chart. That is, initially a chart might have the axes: X - ID, Y - Length, and then after the user changes the view (either via lisbox, radiobutton, etc) the chart would display the information: X - Length, Y - ID, and after a third change by the user it might display new content: X - ID, Y - Quality. My initial thought was that the best way to do this would be to change the bindings themselves. But I don't know how tell a control in XAML to bind using a Binding object in the ViewModel, or whether it's safe to change that binding in runtime? Then I thought maybe I could just have a generic Model that has members X and Y and populate them as needed in the viewmodel? My last thought was that I could have 3 different chart controls and just hide and show them as appropriate. What is the CORRECT/SUGGESTED way to do this in the MVVM pattern? Any code examples would be greatly appreciated. Thanks

    Read the article

  • How to implement two way binding between an ActiveX control and a WPF MVVM View Model

    - by Zamboni
    I have a WPF application implemented using the MVVM framework that uses an ActiveX control and I need to keep the WPF and ActiveX UI synchronised. So far I can update the ActiveX UI when I change the WPF UI using the code at the bottom of the question that I got from the article Hosting an ActiveX Control in WPF and this question. But I cannot update the WPF UI when I make a change in the ActiveX UI. I suspect that I need to fire the PropertyChanged event from my ActiveX control but I have no idea how to do this or if it is even possible. The ActiveX controls I have written are in VB6 and MFC as I am just prototying at this time for the eventual integration of VB6 ActiveX controls in a WPF contaner application. Here is a code snipet that indicates the work done so far: System.Windows.Forms.Integration.WindowsFormsHost host = new System.Windows.Forms.Integration.WindowsFormsHost(); // Create the ActiveX control. AxTEXTBOXActiveXLib.AxTEXTBOXActiveX axWmp = new AxTEXTBOXActiveXLib.AxTEXTBOXActiveX(); // Assign the ActiveX control as the host control's child. host.Child = axWmp; axWmp.DataBindings.Add(new System.Windows.Forms.Binding("ActiveXStatus", (MainWindowViewModel)this.DataContext, "ModelStatus", true, DataSourceUpdateMode.OnPropertyChanged )); // Add the interop host control to the Grid // control's collection of child controls. this.activexRow.Children.Add(host); How to implement two way binding between an ActiveX control and a WPF MVVM View Model?

    Read the article

  • MVVM: Thin ViewModels and Rich Models

    - by Dan Bryant
    I'm continuing to struggle with the MVVM pattern and, in attempting to create a practical design for a small/medium project, have run into a number of challenges. One of these challenges is figuring out how to get the benefits of decoupling with this pattern without creating a lot of repetitive, hard-to-maintain code. My current strategy has been to create 'rich' Model classes. They are fully aware that they will be consumed by an MVVM pattern and implement INotifyPropertyChanged, allow their collections to be observed and remain cognizant that they may always be under observation. My ViewModel classes tend to be thin, only exposing properties when data actually needs to be transformed, with the bulk of their code being RelayCommand handlers. Views happily bind to either ViewModels or Models directly, depending on whether any data transformation is required. I use AOP (via Postsharp) to ease the pain of INotifyPropertyChanged, making it easy to make all of my Model classes 'rich' in this way. Are there significant disadvantages to using this approach? Can I assume that the ViewModel and View are so tightly coupled that if I need new data transformation for the View, I can simply add it to the ViewModel as needed?

    Read the article

  • MVVM Listbox DataTemplate SelectedItem

    - by StinkerPeter
    I am using a ListBox with a DataTemplate as shown below (xaml simplified and variable names changed). <ListBox ItemsSource="{Binding Path=ObservCollectionItems}" SelectedItem="{Binding Path=SelectedItemVar, Mode=TwoWay}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding SomeVar}" /> <Border> <StackPanel> <Button Content="String1" Command="{Binding DataContext.Command1} RelativeSource={RelativeSource FindAncestor, ListBox, 1}}" /> <Button Content="String2" Command="{Binding DataContext.Command2} RelativeSource={RelativeSource FindAncestor, ListBox, 1}}" /> </StackPanel> </Border> </StackPanel> </DataTemplate> <ListBox.ItemTemplate> </ListBox> I need the SelectedItemVar (dependency property) to update when I click on one of the buttons. SelectedItemVar is then used for the respective button's command. SelectedItemVar does update when I click on the TextBlock or the Border, but not when I click either button. I found a non-MVVM solution to this problem here. I do not want to add code in the file-behind to solve this, as they did in the link. Is there a clean solution that can be done in XAML. Beyond the non-MVVM solutions, I have not found anyone with this problem. I would have thought this was fairly common. Finally, I found this Command="{Binding DataContext.CommandName} RelativeSource={RelativeSource FindAncestor, ListBox, 1} for the Command binding. I do not fully understand what it is doing, but I do know that the command wasn't firing when I was binding directly to CommandName.

    Read the article

  • Programatically adding,changing and removing controls bound to model objects (MVVM)

    - by Ittai
    I have the following scenario and I'm trying to decide how it can and should be implemented in silverlight and c# via MVVM. Scenario: I have the following objects in my scenario: MyModel, MyModelControl, MyView and MyViewModel. MyModelcontrol is a custom UserControl of mine and the rest I think are pretty much self explanatory. MyViewModel is a Subscriber of a message which hands it a Collection<MyModel> newCol and let's mark curCol as the current Collection<MyModel> that MyViewModel holds. I then want to programatically add MyModelControl controls for each MyModel instance which belongs to newCol and not to curCol. I also want to bind the MyModelControl instance to the corresponding MyModel instance. In a similar manner I want to remove the controls which don't belong now to the collection and I want to update a property for those which belong to both. I do not want to remove all controls which belong to curCol and then add all controls for newCol as the creation of MyModelControl is "expensive". I'd appreciate help with how this should be implemented in SL as I'm new to it and to the MVVM pattern. Comments regarding the design would also be welcomed. B.T.W This will run on Windows Phone 7 so I think there are some limitations on versions, if this is an issue please comment and I'll verify which versions exactly I can use on the phone.

    Read the article

  • MVVM Light Toolkit throws an System.IO.FileLoadException

    - by joebeazelman
    I'm running VS 2010 along with Expression Blend 4 beta. I created a MVVM Light project from the supplied templates and I get a System.IO.FileLoadException when I try to view the MainWindow.Xaml in VS 2010 designer window. The template already references System.Windows.Interactivity. Here are the details of the exception: System.IO.FileLoadException Could not load file or assembly 'System.Windows.Interactivity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515) at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.Assembly.Load(AssemblyName assemblyRef) at MS.Internal.Package.VSIsolationProviderService.RemoteReferenceProxy.VsReflectionResolver.GetRuntimeAssembly(Assembly reflectionAssembly) at Microsoft.Windows.Design.Metadata.ReflectionMetadataContext.CachingReflectionResolver.GetRuntimeAssembly(Assembly reflectionAssembly) at Microsoft.Windows.Design.Metadata.ReflectionMetadataContext.Microsoft.Windows.Design.Metadata.IReflectionResolver.GetRuntimeAssembly(Assembly reflectionAssembly) at MS.Internal.Metadata.ClrAssembly.GetRuntimeMetadata(Object reflectionMetadata) at Microsoft.Windows.Design.Metadata.AttributeTableContainer.d_c.MoveNext() at Microsoft.Windows.Design.Metadata.AttributeTableContainer.GetAttributes(Assembly assembly, Type attributeType, Func`2 reflectionMapper) at MS.Internal.Metadata.ClrAssembly.GetAttributes(ITypeMetadata attributeType) at MS.Internal.Design.Metadata.Xaml.XamlAssembly.get_XmlNamespaceCompatibilityMappings() at Microsoft.Windows.Design.Metadata.Xaml.XamlExtensionImplementations.GetXmlNamespaceCompatibilityMappings(IAssemblyMetadata sourceAssembly) at Microsoft.Windows.Design.Metadata.Xaml.XamlExtensions.GetXmlNamespaceCompatibilityMappings(IAssemblyMetadata source) at MS.Internal.Design.Metadata.ReflectionProjectNode.BuildSubsumption() at MS.Internal.Design.Metadata.ReflectionProjectNode.SubsumingNamespace(Identifier identifier) at MS.Internal.Design.Markup.XmlElement.BuildScope(PrefixScope parentScope, IParseContext context) at MS.Internal.Design.Markup.XmlElement.ConvertToXaml(XamlElement parent, PrefixScope parentScope, IParseContext context, IMarkupSourceProvider provider) at MS.Internal.Design.DocumentModel.DocumentTrees.Markup.XamlSourceDocument.FullParse(Boolean convertToXamlWithErrors) at MS.Internal.Design.DocumentModel.DocumentTrees.Markup.XamlSourceDocument.get_RootItem() at Microsoft.Windows.Design.DocumentModel.Trees.ModifiableDocumentTree.get_ModifiableRootItem() at Microsoft.Windows.Design.DocumentModel.MarkupDocumentManagerBase.get_LoadState() at MS.Internal.Host.PersistenceSubsystem.Load() at MS.Internal.Host.Designer.Load() at MS.Internal.Designer.VSDesigner.Load() at MS.Internal.Designer.VSIsolatedDesigner.VSIsolatedView.Load() at MS.Internal.Designer.VSIsolatedDesigner.VSIsolatedDesignerFactory.Load(IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.BootstrapProxy.LoadDesigner(IsolatedDesignerFactory factory, IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.BootstrapProxy.LoadDesigner(IsolatedDesignerFactory factory, IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.Load() at MS.Internal.Designer.DesignerPane.LoadDesignerView() System.NotSupportedException An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See http://go.microsoft.com/fwlink/?LinkId=155569 for more information.

    Read the article

  • What&rsquo;s new in MVVM Light V3

    - by Laurent Bugnion
    V3 of the MVVM Light Toolkit was released during MIX10, after quite a long alpha stage. This post lists the new features in MVVM Light V3. Compatibility MVVM Light Toolkit V3 can be installed for the following tools and framework versions: Visual Studio 2008 SP1, Expression Blend 3 Windows Presentation Foundation 3.5 SP1 Silverlight 3 Visual Studio 2010 RC, Expression Blend 4 beta Windows Presentation Foundation 3.5 SP1 Windows Presentation Foundation 4 RC Silverlight 3 Silverlight 4 RC For more information about installing the MVVM Light Toolkit V3, please visit this page. For cleaning up existing installation, see this page. New in V3 RTM The following features have been added after V3 alpha3: Project template for the Windows Phone 7 series (Silverlight) This new template allows you to create a new MVVM Light application in Visual Studio 2010 RC and to run it in the Windows Phone 7 series emulator. This template uses the Silverlight 3 version of the MVVM Light Toolkit V3. At this time, only the essentials features of the GalaSoft.MvvmLight.dll assembly are supported on the phone. New in V3 alpha3 The following features have been added after V3 alpha2: New logo An awesome logo has been designed for MVVM Light by Philippe Schutz. DispatcherHelper class (in GalaSoft.MvvmLight.Extras.dll) This class is useful when you work on multi-threaded WPF or Silverlight applications. Initializing: The DispatcherHelper class must be initialized in the UI thread. For example, you can initialize the class in a Silverlight application’s Application_Startup event handler, or in the WPF application’s static App constructor (in App.xaml). // Initializing in Silverlight (in App.xaml) private void Application_Startup( object sender, StartupEventArgs e) { RootVisual = new MainPage(); DispatcherHelper.Initialize(); } // Initializing in WPF (in App.xaml) static App() { DispatcherHelper.Initialize(); } Verifying if a property exists The ViewModelBase.RaisePropertyChanged method now checks if a given property name exists on the ViewModel class, and throws an exception if that property cannot be found. This is useful to detect typos in a property name, for example during a refactoring. Note that the check is only done in DEBUG mode. Replacing IDisposable with ICleanup The IDisposable implementation in the ViewModelBase class has been marked obsolete. Instead, the ICleanup interface (and its Cleanup method) has been added. Implementing IDisposable in a ViewModel is still possible, but must be done explicitly. IDisposable in ViewModelBase was a bad practice, because it supposes that the ViewModel is garbage collected after Dispose is called. instead, the Cleanup method does not have such expectation. The ViewModelLocator class (created when an MVVM Light project template is used in Visual Studio or Expression Blend) exposes a static Cleanup method, which should in turn call each ViewModel’s Cleanup method. The ViewModel is free to override the Cleanup method if local cleanup must be performed. Passing EventArgs to command with EventToCommand The EventToCommand class is used to bind any event to an ICommand (typically on the ViewModel). In this case, it can be useful to pass the event’s EventArgs parameter to the command in the ViewModel. For example, for the MouseEnter event, you can pass the MouseEventArgs to a RelayCommand<MouseEventArgs> as shown in the next listings. Note: Bringing UI specific classes (such as EventArgs) into the ViewModel reduces the testability of the ViewModel, and thus should be used with care. Setting EventToCommand and PassEventArgsToCommand: <Grid x:Name="LayoutRoot"> <i:Interaction.Triggers> <i:EventTrigger EventName="MouseEnter"> <cmd:EventToCommand Command="{Binding MyCommand}" PassEventArgsToCommand="True" /> </i:EventTrigger> </i:Interaction.Triggers> </Grid> Getting the EventArgs in the command public RelayCommand<MouseEventArgs> MyCommand { get; private set; } public MainViewModel() { MyCommand = new RelayCommand<MouseEventArgs>(e => { // e is of type MouseEventArgs }); } Changes to templates Various changes have been made to project templates and item templates to make them more compatible with Silverlight 4 and to improve their visibility in Visual Studio and Expression Blend. Bug corrections When a message is sent through the Messenger class using the method Messenger.Default.Send<T>(T message, object token), and the token is a simple value (for example int), the message was not sent correctly. This bug is now corrected. New in V3 The following features have been added after V2. Sending messages with callback Certain classes have been added to the GalaSoft.MvvmLight.Messaging namespace, allowing sending a message and getting a callback from the recipient. These classes are: NotificationMessageWithCallback: Base class for messages with callback. NotificationMessageAction: A class with string notification, and a parameterless callback. NotificationMessageAction<T>: A class with string notification, and a callback with a parameter of type T. To send a message with callback, use the following code: var message = new NotificationMessageAction<bool>( "Hello world", callbackMessage => { // This is the callback code if (callbackMessage) { // ... } }); Messenger.Default.Send(message); To register and receive a message with callback, use the following code: Messenger.Default.Register<NotificationMessageAction<bool>>( this, message => { // Do something // Execute the callback message.Execute(true); }); Messenger.Default can be overriden The Messenger.Default property can also be replaced, for example for unit testing purposes, by using the Messenger.OverrideDefault method. All the public methods of the Messenger class have been made virtual, and can be overridden in the test messenger class. Sending messages to interfaces In V2, it was possible to deliver messages targeted to instances of a given class. in V3 it is still possible, but in addition you can deliver a message to instances that implement a certain interface. The message will not be delivered to other recipients. Use the overload Messenger.Default.Send<TMessage, TTarget>(TMessage message) where TTarget is, in fact, an interface (for example IDisposable). Of course the recipient must register to receive the type of message TMessage. Sending messages with a token Messages can now be sent through the Messenger with a token. To send a message with token, use the method overload Send<TMessage>(TMessage message, object token). To receive a message with token, use the methods Register<TMessage>(object recipient, object token, Action<TMessage> action) or Register<TMessage>(object recipient, object token, bool receiveDerivedMessagesToo, Action<TMessage> action) The token can be a simple value (int, string, etc…) or an instance of a class. The message is not delivered to recipients who registered with a different token, or with no token at all. Renaming CommandMessage to NotificationMessage To avoid confusion with ICommand and RelayCommand, the CommandMessage class has been renamed to NotificationMessage. This message class can be used to deliver a notification (of type string) to a recipient. ViewModelBase constructor with IMessenger The ViewModelBase class now accepts an IMessenger parameter. If this constructor is used instead of the default empty constructor, the IMessenger passed as parameter will be used to broadcast a PropertyChangedMessage when the method RaisePropertyChanged<T>(string propertyName, T oldValue, T newValue, bool broadcast) is used. In the default ViewModelBase constructor is used, the Messenger.Default instance will be used instead. EventToCommand behavior The EventToCommand behavior has been added in V3. It can be used to bind any event of any FrameworkElement to any ICommand (for example a RelayCommand located in the ViewModel). More information about the EventToCommand behavior can be found here and here. Updated the project templates to remove the sample application The project template has been updated to remove the sample application that was created every time that a new MVVM Light application was created in Visual Studio or Blend. This makes the creation of a new application easier, because you don’t need to remove code before you can start writing code. Bug corrections Some bugs that were in Version 2 have been corrected: In some occasions, an exception could be thrown when a recipient was registered for a message at the same time as a message was received. New names for DLLs If you upgrade an existing installation, you will need to change the reference to the DLLs in C:\Program Files\Laurent Bugnion (GalaSoft)\Mvvm Light Toolkit\Binaries. The assemblies have been moved, and the versions for Silverlight 4 and for WPF4 have been renamed, to avoid some confusion. It is now easier to make sure that you are using the correct DLL. WPF3.5SP1, Silverlight 3 When using the DLLs, make sure that you use the correct versions. WPF4, Silverlight 4 When using the DLLs, make sure that you use the correct versions.   Laurent Bugnion (GalaSoft) Subscribe | Twitter | Facebook | Flickr | LinkedIn

    Read the article

  • What conventions or frameworks exist for MVVM in Perl?

    - by Will Sheppard
    We're using Catalyst to render lots of webforms in what will become a large application. I don't like the way all the form data is confusingly into a big hash in the Controller, before being passed to the template. It seems jumbled up and messy for the template. I'm sure there are real disadvantages that I haven't described properly... Are there? One solution is to just decide on a convention for the hash, e.g.: { defaults => { type => ['a', 'b', 'c'] }, input => { type => 'a' }, output => { message => "2 widgets found of type a", widgets => [ 'foo', 'bar' ] } } Another way is to store the page/form data as attributes in a class (a ViewModel?), and pass a whole object to the template, which it could use like this: <p class="message">[% model.message %]<p> [% FOREACH widget IN model.widgets %] Which way is more flexible for large applications? Are there any other solutions or existing Catalyst-compatible frameworks?

    Read the article

  • Help understand GLSL directional light on iOS (left handed coord system)

    - by Robse
    I now have changed from GLKBaseEffect to a own shader implementation. I have a shader management, which compiles and applies a shader to the right time and does some shader setup like lights. Please have a look at my vertex shader code. Now, light direction should be provided in eye space, but I think there is something I don't get right. After I setup my view with camera I save a lightMatrix to transform the light from global space to eye space. My modelview and projection setup: - (void)setupViewWithWidth:(int)width height:(int)height camera:(N3DCamera *)aCamera { aCamera.aspect = (float)width / (float)height; float aspect = aCamera.aspect; float far = aCamera.far; float near = aCamera.near; float vFOV = aCamera.fieldOfView; float top = near * tanf(M_PI * vFOV / 360.0f); float bottom = -top; float right = aspect * top; float left = -right; // projection GLKMatrixStackLoadMatrix4(projectionStack, GLKMatrix4MakeFrustum(left, right, bottom, top, near, far)); // identity modelview GLKMatrixStackLoadMatrix4(modelviewStack, GLKMatrix4Identity); // switch to left handed coord system (forward = z+) GLKMatrixStackMultiplyMatrix4(modelviewStack, GLKMatrix4MakeScale(1, 1, -1)); // transform camera GLKMatrixStackMultiplyMatrix4(modelviewStack, GLKMatrix4MakeWithMatrix3(GLKMatrix3Transpose(aCamera.orientation))); GLKMatrixStackTranslate(modelviewStack, -aCamera.position.x, -aCamera.position.y, -aCamera.position.z); } - (GLKMatrix4)modelviewMatrix { return GLKMatrixStackGetMatrix4(modelviewStack); } - (GLKMatrix4)projectionMatrix { return GLKMatrixStackGetMatrix4(projectionStack); } - (GLKMatrix4)modelviewProjectionMatrix { return GLKMatrix4Multiply([self projectionMatrix], [self modelviewMatrix]); } - (GLKMatrix3)normalMatrix { return GLKMatrix3InvertAndTranspose(GLKMatrix4GetMatrix3([self modelviewProjectionMatrix]), NULL); } After that, I save the lightMatrix like this: [self.renderer setupViewWithWidth:view.drawableWidth height:view.drawableHeight camera:self.camera]; self.lightMatrix = [self.renderer modelviewProjectionMatrix]; And just before I render a 3d entity of the scene graph, I setup the light config for its shader with the lightMatrix like this: - (N3DLight)transformedLight:(N3DLight)light transformation:(GLKMatrix4)matrix { N3DLight transformedLight = N3DLightMakeDisabled(); if (N3DLightIsDirectional(light)) { GLKVector3 direction = GLKVector3MakeWithArray(GLKMatrix4MultiplyVector4(matrix, light.position).v); direction = GLKVector3Negate(direction); // HACK -> TODO: get lightMatrix right! transformedLight = N3DLightMakeDirectional(direction, light.diffuse, light.specular); } else { ... } return transformedLight; } You see the line, where I negate the direction!? I can't explain why I need to do that, but if I do, the lights are correct as far as I can tell. Please help me, to get rid of the hack. I'am scared that this has something to do, with my switch to left handed coord system. My vertex shader looks like this: attribute highp vec4 inPosition; attribute lowp vec4 inNormal; ... uniform highp mat4 MVP; uniform highp mat4 MV; uniform lowp mat3 N; uniform lowp vec4 constantColor; uniform lowp vec4 ambient; uniform lowp vec4 light0Position; uniform lowp vec4 light0Diffuse; uniform lowp vec4 light0Specular; varying lowp vec4 vColor; varying lowp vec3 vTexCoord0; vec4 calcDirectional(vec3 dir, vec4 diffuse, vec4 specular, vec3 normal) { float NdotL = max(dot(normal, dir), 0.0); return NdotL * diffuse; } ... vec4 calcLight(vec4 pos, vec4 diffuse, vec4 specular, vec3 normal) { if (pos.w == 0.0) { // Directional Light return calcDirectional(normalize(pos.xyz), diffuse, specular, normal); } else { ... } } void main(void) { // position highp vec4 position = MVP * inPosition; gl_Position = position; // normal lowp vec3 normal = inNormal.xyz / inNormal.w; normal = N * normal; normal = normalize(normal); // colors vColor = constantColor * ambient; // add lights vColor += calcLight(light0Position, light0Diffuse, light0Specular, normal); ... }

    Read the article

  • Are all View Models supposed to be accessed through the Main View Model in MVVM?

    - by chustar
    I am currently working on a WP8 application. My current design is to have each view bind against a specific view model directly. Looking through the samples though, it seems that another way is to have all the view models accessed through the Main View Model and then have all the views to their view models through the MVM. Is this the correct way to do it (So that it doesn't cause flexibility and other issues in the future)?

    Read the article

  • When using MVVM, should you create new viewmodels, or swap out the models?

    - by ConditionRacer
    Say I have a viewmodel like this: public class EmployeeViewModel { private EmployeeModel _model; public Color BackgroundColor { get; set; } public Name { get { return _model.Name; } set { _model.Name = value; NotifyPropertyChanged(Name); } } } So this viewmodel binds to a view that displays an employee. The thing to think about is, does this viewmodel represent an employee, or a "displayable" employee. The viewmodel contains some things that are view specific, for instance the background color. There can be many employees, but only one employee view. With this in mind, when changing the displayed employee, does it make sense to create a new EmployeeViewModel and rebind to the view, or simply swap out the EmployeeModel. Is the distinction even important, or is it a matter of style? I've always leaned toward creating new viewmodels, but I am working on a project where the viewmodels are created once and the models are swapped out. I'm not sure how I feel about this, though it seems to work fine.

    Read the article

  • WPF ComboBox Binding to non string object

    - by Mike L
    I'm using MVVM (MVVM Light Toolkit) and have a property on the view model which exposes a list of objects. The objects contain two properties, both strings, which correlate to an abbreviation and a description. I want the ComboBox to expose the pairing as "abbreviation - description". If I use a data template, it does this easily. I have another property on the view model which represents the object that should display as selected -- the chosen item in the ComboBox. I'm binding the ItemsSource to the list, as it represents the universe of available selections, and am trying to bind the SelectedItem to this object. I'm killing myself trying to figure out why I can't get it to work, and feeling more like a fraud by the hour. In trying to learn why this works, I created the same approach with just a list of strings, and a selected string. This works perfectly. So, it clearly has something to do with the typing... perhaps something in choosing equality? Or perhaps it has to do with the data template? Here is the XAML: <Window x:Class="MvvmLight1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="300" Width="300" DataContext="{Binding Main, Source={StaticResource Locator}}"> <Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Skins/MainSkin.xaml" /> </ResourceDictionary.MergedDictionaries> <DataTemplate x:Key="DataTemplate1"> <StackPanel Orientation="Horizontal"> <TextBlock TextWrapping="Wrap" Text="{Binding CourtCode}"/> <TextBlock TextWrapping="Wrap" Text=" - "/> <TextBlock TextWrapping="Wrap" Text="{Binding CourtDescription}"/> </StackPanel> </DataTemplate> </ResourceDictionary> </Window.Resources> <Grid x:Name="LayoutRoot"> <ComboBox x:Name="cmbAbbrevDescriptions" Height="35" Margin="25,75,25,25" VerticalAlignment="Top" ItemsSource="{Binding Codes}" ItemTemplate="{DynamicResource DataTemplate1}" SelectedItem="{Binding selectedCode}" /> <ComboBox x:Name="cmbStrings" Height="35" Margin="25" VerticalAlignment="Top" ItemsSource="{Binding strs}" SelectedItem="{Binding selectedStr}"/> </Grid> </Window> And, if helpful, here is the ViewModel: using GalaSoft.MvvmLight; using MvvmLight1.Model; using System.Collections.Generic; namespace MvvmLight1.ViewModel { public class MainViewModel : ViewModelBase { public const string CodesPropertyName = "Codes"; private List<Court> _codes = null; public List<Court> Codes { get { return _codes; } set { if (_codes == value) { return; } var oldValue = _codes; _codes = value; // Update bindings and broadcast change using GalaSoft.Utility.Messenging RaisePropertyChanged(CodesPropertyName, oldValue, value, true); } } public const string selectedCodePropertyName = "selectedCode"; private Court _selectedCode = null; public Court selectedCode { get { return _selectedCode; } set { if (_selectedCode == value) { return; } var oldValue = _selectedCode; _selectedCode = value; // Update bindings and broadcast change using GalaSoft.Utility.Messenging RaisePropertyChanged(selectedCodePropertyName, oldValue, value, true); } } public const string strsPropertyName = "strs"; private List<string> _strs = null; public List<string> strs { get { return _strs; } set { if (_strs == value) { return; } var oldValue = _strs; _strs = value; // Update bindings and broadcast change using GalaSoft.Utility.Messenging RaisePropertyChanged(strsPropertyName, oldValue, value, true); } } public const string selectedStrPropertyName = "selectedStr"; private string _selectedStr = ""; public string selectedStr { get { return _selectedStr; } set { if (_selectedStr == value) { return; } var oldValue = _selectedStr; _selectedStr = value; // Update bindings and broadcast change using GalaSoft.Utility.Messenging RaisePropertyChanged(selectedStrPropertyName, oldValue, value, true); } } /// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel() { Codes = new List<Court>(); Court code1 = new Court(); code1.CourtCode = "ABC"; code1.CourtDescription = "A Court"; Court code2 = new Court(); code2.CourtCode = "DEF"; code2.CourtDescription = "Second Court"; Codes.Add(code1); Codes.Add(code2); Court code3 = new Court(); code3.CourtCode = "DEF"; code3.CourtDescription = "Second Court"; selectedCode = code3; selectedStr = "Hello"; strs = new List<string>(); strs.Add("Goodbye"); strs.Add("Hello"); strs.Add("Ciao"); } } } And here is the ridiculously trivial class that is being exposed: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MvvmLight1.Model { public class Court { public string CourtCode { get; set; } public string CourtDescription { get; set; } } } Thanks!

    Read the article

  • MVVM- How would I go about propagating settings between my main view-model (and other view-models) a

    - by Justin
    I am building a settings dialog for my application and right now all of the settings correspond with settings on the main view-model, but as I add more view's and view-models some may not. I need to know what the best practice is for loading the current settings into the settings dialog and then saving the settings to thier corresponding view-models if the user clicks okay. I will not be using the Properties.Settings.Default system to store settings since I want my application to be as portable as possible and this would store user scoped settings in the directory: C:\Users\ username \Local Settings\Application Data\ ApplicationName Instead of in my application's directory. In case it makes any difference I am using the MVVM Light Toolkit by Laurent Bugnion.

    Read the article

  • point light illumination using Phong model

    - by Myx
    Hello: I wish to render a scene that contains one box and a point light source using the Phong illumination scheme. The following are the relevant code snippets for my calculation: R3Rgb Phong(R3Scene *scene, R3Ray *ray, R3Intersection *intersection) { R3Rgb radiance; if(intersection->hit == 0) { radiance = scene->background; return radiance; } ... // obtain ambient term ... // this is zero for my test // obtain emissive term ... // this is also zero for my test // for each light in the scene, obtain calculate the diffuse and specular terms R3Rgb intensity_diffuse(0,0,0,1); R3Rgb intensity_specular(0,0,0,1); for(unsigned int i = 0; i < scene->lights.size(); i++) { R3Light *light = scene->Light(i); R3Rgb light_color = LightIntensity(scene->Light(i), intersection->position); R3Vector light_vector = -LightDirection(scene->Light(i), intersection->position); // check if the light is "behind" the surface normal if(normal.Dot(light_vector)<=0) continue; // calculate diffuse reflection if(!Kd.IsBlack()) intensity_diffuse += Kd*normal.Dot(light_vector)*light_color; if(Ks.IsBlack()) continue; // calculate specular reflection ... // this I believe to be irrelevant for the particular test I'm doing } radiance = intensity_diffuse; return radiance; } R3Rgb LightIntensity(R3Light *light, R3Point position) { R3Rgb light_intensity; double distance; double denominator; if(light->type != R3_DIRECTIONAL_LIGHT) { distance = (position-light->position).Length(); denominator = light->constant_attenuation + (light->linear_attenuation*distance) + (light->quadratic_attenuation*distance*distance); } switch(light->type) { ... case R3_POINT_LIGHT: light_intensity = light->color/denominator; break; ... } return light_intensity; } R3Vector LightDirection(R3Light *light, R3Point position) { R3Vector light_direction; switch(light->type) { ... case R3_POINT_LIGHT: light_direction = position - light->position; break; ... } light_direction.Normalize(); return light_direction; } I believe that the error must be somewhere in either LightDirection(...) or LightIntensity(...) functions because when I run my code using a directional light source, I obtain the desired rendered image (thus this leads me to believe that the Phong illumination equation is correct). Also, in Phong(...), when I computed the intensity_diffuse and while debugging, I divided light_color by 10, I was obtaining a resulting image that looked more like what I need. Am I calculating the light_color correctly? Thanks.

    Read the article

  • Starting an animation from the ViewModel in WPF/MVVM

    - by RandomEngy
    I'm writing a MVVM app and have started putting in a few animations. I want to call something on the ViewModel which starts the a storyboard. This blog had a promising approach to it, but it doesn't actually work. The IDChanged handler never fires for some reason. I also found that you could start animations on EventTriggers, but I don't know how to raise one on the ViewModel.

    Read the article

  • dynamic ContextMenu in TreeView vs. MVVM

    - by bitbonk
    I have a tree of ViewModels displayed as a TreeView (using HierarchicalDataTemplate). Each ViewModel instance has different commands that can be executed on it wich again are exposed as a list of command ViewModels for each item ViewModel. How can I create a single ContextMenu that opens at the TreeViewItem that was rightclicked and that populates its commands from the underlying item ViewModel's command ViewModels list? All in a decent MVVM fashion ...

    Read the article

  • MVVM Binding to Properties.Settings

    - by LnDCobra
    In a MVVM approach how would I go about binding to Properties.Settings? Is there a way to bind a property in C# code(in the ViewModel) to another property(Properties.Settings.Default) or should i just bind to standard properties and on save make sure each property gets propogated manually to the Properties.Settings?

    Read the article

  • how to load wpf usercontrol in MVVM pattern

    - by Anish
    Hi, I'm creating a wpf user control which is in mvvm pattern. So we have : view(with no code in codebehind file), viewmodel,model,dataaccess files. I have MainWindow.xaml as a view file, which I need to bind with MainWindowModel.cs. Usually, in a a wpf application we can do this with onStartUp event in App.xaml file. But in user control, as we do not have App.xaml...How do I achieve it ? Please help :(...Thanks in Advance !!!

    Read the article

  • Modelling a checkable treeview in the MVVM model

    - by Stephen Stranded
    Hi, I am trying to create a checkable treeview control to list hierarchical data but it does not seem to work. I used the MVVM model example used by in codeplex simplified Treeview using ViewModel but it shows nothing. Here is my code. Please help. I am a newbie to WPF and the MVVM model but i very much want to use it in an urgent application. </UserControl.Resources> <Grid> <StackPanel Height="166"> <TextBlock Text="Please Display this" /> <TreeView ItemsSource="{Binding Classifications}" Height="141"> <TreeView.ItemContainerStyle> <!-- This Style binds a TreeViewItem to a TreeViewItemViewModel. --> <Style TargetType="{x:Type TreeViewItem}"> <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" /> <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" /> <Setter Property="FontWeight" Value="Normal" /> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="FontWeight" Value="Bold" /> </Trigger> </Style.Triggers> </Style> </TreeView.ItemContainerStyle> <TreeView.Resources> <HierarchicalDataTemplate DataType="{x:Type local:PropertyTypeViewModel}" ItemsSource="{Binding Children}"> <StackPanel Orientation="Horizontal"> <CheckBox Focusable="false" IsChecked="{Binding isSelected}"></CheckBox> <TextBlock Text="{Binding Classification}" /> </StackPanel> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="{x:Type local:PropertyViewModel}" ItemsSource="{Binding Children}" > <StackPanel Orientation="Horizontal"> <CheckBox Focusable="false" IsChecked="{Binding isSelected}"></CheckBox> <TextBlock Text="{Binding PropertyName}" /> </StackPanel> </HierarchicalDataTemplate> <DataTemplate DataType="{x:Type local:LeaseViewModel}"> <StackPanel Orientation="Horizontal"> <CheckBox Focusable="false" IsChecked="{Binding isSelected}"></CheckBox> <TextBlock Text="{Binding TenantName}" /> </StackPanel> </DataTemplate> </TreeView.Resources> </TreeView> </StackPanel> </Grid>

    Read the article

  • ASP.NET MVC, MVVM and file uploads...

    - by Kieron
    Hi, I'm big fan of the MVVM pattern, in particular while using the ASP.NET MVC Framework (in this case v2 preview 2). But I'm curious if anyone knows how to use it when doing file uploads? public class MyViewModel { public WhatTypeShouldThisBe MyFileUpload { get; set; } }

    Read the article

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