Git Product home page Git Product logo

lbugnion / mvvmlight Goto Github PK

View Code? Open in Web Editor NEW
1.2K 67.0 311.0 43.14 MB

The main purpose of the toolkit is to accelerate the creation and development of MVVM applications in Xamarin.Android, Xamarin.iOS, Xamarin.Forms, Windows 10 UWP, Windows Presentation Foundation (WPF), Silverlight, Windows Phone.

Home Page: http://www.mvvmlight.net

License: MIT License

C# 92.42% Batchfile 3.79% Pascal 0.23% PowerShell 0.51% Vim Snippet 3.05%
mvvm-light-toolkit mvvm mvvmlight model-view-viewmodel cross-platform xamarin xamarin-android xamarin-ios xamarin-forms windows

mvvmlight's Introduction

MVVM Light Toolkit

MVVM Light is not maintained anymore. Over the years, thousands of users have found this project useful with millions of downloads. We are truly overwhelmed by the kindness shown by a huge amount of members of this awesome community. Thanks so much for making this little project so popular and for making it all worthwhile.

We strongly recommend looking into the Microsoft MVVM Toolkit, an open source project from the Windows Community Toolkit, as the successor of MVVM Light.

The main purpose of the toolkit is to accelerate the creation and development of MVVM applications in Xamarin.Android, Xamarin.iOS, Xamarin.Forms, Windows 10 UWP, Windows Presentation Foundation (WPF), Silverlight, Windows Phone.

Get started

More information about the MVVM Light Toolkit can be found on http://www.mvvmlight.net.

Documentation: See http://www.mvvmlight.net/doc

Nuget versions

MvvmLightLibs MvvmLight MvvmLightAndroidSupport MvvmLightLibsStd10 MvvmLightStd10

VSIX packages for Visual Studio

VS2012 VS2013 VS2015 VS2017

License

Under MIT License.

mvvmlight's People

Contributors

gianlucaparadise avatar janschreier avatar jzeferino avatar lbugnion avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mvvmlight's Issues

Async Messenger

It would be great if it was possible to await a Messenger.Send method when the registered method is async.

For example:

class Caller : ViewModelBase
{
	async Task CallingMethod()
	{
		// Do things
		
		await this.MessengerInstance.SendAsync(new Message());
		
		// Do other things
	}
}

class Receiver : ViewModelBase
{
	Receiver()
	{
		this.MessengerInstance.RegisterAsync<Message>(this, OnMessageAsync);
	}
	
	private async Task OnMessageAsync(Navigation msg)
	{
		await AsyncThingsOnReceive();
	}
}

I don't even know if this is possible regarding to your architecture. This guy made an attempt to solve this issue but I think it is not compatible with the last version of MVVM Light : https://github.com/runceel/AsyncMessenger.

Enum value as CommandParameter causes CanExecute not to be called in UWP

Steps to reproduce

  • Create empty UWP app.
  • Create the following enum:
public enum ActionType
{
    FirstAction = 0,
    SecondAction = 1
}
  • Create one sample page with a view model and add a button to the page (adding the enums namespace as well)
<Button Command="{Binding TestCommand}">
    <Button.CommandParameter>
        <enums:ActionType>SecondAction</enums:ActionType>
    </Button.CommandParameter>
</Button>
  • In the viewmodel, create the command:
TestCommand = new RelayCommand<ActionType> (Execute, CanExecute);
  • And implement them like this:
private void Execute(ActionType value) => Debug.WriteLine(value);
private void CanExecute(ActionType value) => Debug.WriteLine(value);
  • Now call TestCommand.RaiseCanExecuteChanged() in the ViewModel constructor or in on another button click

  • Observe CanExecute is never called and the button is always disabled.

Issue source

I have debugged the code and found this check in RelayCommand.CanExecute:

if (parameter == null || parameter is T)
{
    return (_canExecute.Execute((T)parameter));
}

However when enum is used as command parameter, the parameter is for some reason int only, not ActionType this means the check parameter is T fails and CanExecute always returns false.

No release branches any more?

Hi, I just can't find the release branch after V5.4.
have you guys just begin to use the master branch for releasing? just got confusing now.

Missing method of SimpleIoc.Default.Register

I get types and interface in the Assembly, so I can't use

SimpleIoc.Default.Register<IDataService, DataService>();

can we add the method ?

SimpleIoc.Default.Register(typeInterface, type);

( pulled by nuget )

CanExecuteChanged memory leak in UWP

Hi

I have a view model with a RelayCommand that is bound to the UI. I am reusing a single instance of that view model that is shared between pages. When navigating between pages the old view is thrown away and the single instance is bound to the new page.

I have noticed that the CanExecuteChanged event is being subscribed to by something in the UI and it is never being unsubscribed. The RelayCommand.CanExecuteChanged invocation list grows each time a new page is navigated to forever.

dotMemory:
image

Using the none default instance of messenger in view

I was wondering if you had any techniques for using a custom instance of the messenger in the code behind of a view. I would rather create my own instance of the messenger and pass that around than using the singleton instance. Thanks

Constructor injection based on key with SimpleIoc

In my scenario, I want to inject an instance into a constructor as a parameter based on a key.

Is this something that the SimpleIoc could support, or should I choose another IoC container instead?

I'm thinking about adding support for an InjectAttribute.

Concept:

public class Foo 
{
  public Foo([Inject("bar1")] IBar bar) 
  {

  }
  // Omitted
}

Extract System.Windows.Interactivity.dll to its own nuget package

System.Windows.Interactivity should not be packed with MvvmLightLibs, it should be extracted as a separate NuGet package which MvvmLightLibs depends upon.

We see different locations of System.Windows.Interactivity being referenced in our solution. If System.Windows.Interactivity was extracted to its own NuGet package it would be possible to use the same reference across all projects.

AndroidSupport ObservableRecyclerAdapter and ClickCallback

#Hello,

The ClickCallback is never use when a CreateViewHolderDelegate is given to ObservableRecyclerAdapter. With CellLayoutId, it's work fine.

Potential fix can be :
At line 508 of ObservableRecyclerAdapter file :

return CreateViewHolderDelegate(parent, viewType);

Replace with :

var createViewHolder = CreateViewHolderDelegate(parent, viewType);
var castedCreateViewHolder = createViewHolder as CachingViewHolder;
if (castedCreateViewHolder != null) 
{
         castedCreateViewHolder.ClickCallback = OnItemClick;
}

MvvmLightAndroidSupport - MvvmLightLibsStd10 & MvvmLightLibs

Hi,

In our Xamarin app we have a "Core" .NET Standard that reference the MvvmLightLibsStd10 package.
However, in our Android app, since we use MvvmLightAndroidSupport we are forced to reference both MvvmLightLibsStd10 & MvvmLightLibs (since the latter is a dependency of MvvmLightAndroidSupport).

How could we reference just MvvmLightAndroidSupport and MvvmLightLibsStd10?

Thank you,
Cosmin

MVVM Light adds large number of system assemblies to the installer

When targeting .NET 4.5 or later, adding MVVM Light to my WPF project injects a large number of system assemblies to the application folder upon installation.

Here's how to produce this:

  1. Create a new WPF Application project, targeting .NET 4.5 or above.
  2. Add NuGet reference to MVVM Light (or the Lib-only version; doesn't matter).
  3. Add an MSI Setup project to the solution (extension needs to be installed beforehand).
  4. Add Primary Project Output of WPF application to the setup project.

There you go. A long list of System.X.Y will be added to the list. If you build and install the setup project, you'll see all these DLLs in Program Files folder.

The problem does not appear if WPF application targets .NET Framework 4.0 and you add NuGet reference AFTER that. But if you target .NET 4.5, 4.5.1 or 4.6, the long list of dependencies appears again. Think MVVM Light (or NuGet) is having trouble finding the correct package sub-folder.

PropertyChanged not being called on async methods when switching to commandwpf

Versions: MvvmLightLibs 5.3.0, .NET Framework 4.6.1

This is a WPF App using .NET.

The Issue
We use a dispatcher on async methods to change a property's value and have it updated on the UI thread. This works when we use using GalaSoft.MvvmLight.Command but breaks when switch to using GalaSoft.MvvmLight.CommandWpf. We had to switch to CommandWpf to get the CanExecute working correctly.

Properties that were binded to user controls (like changing the status text) no longer work.

App.Current.Dispatcher.Invoke(new Action(() => this.MyProperty= true));

RelayCommand.RaiseCanExecuteChanged() does nothing under Xamarin

We are porting some WPF code to Xamarin and at one point we have the following method:

public void RaiseCanExecuteChanged() { foreach (var cmd in _relayCommands) { cmd.RaiseCanExecuteChanged(); } }

This works fine under WPF but under Xamarin the exact same code (it's a shared assembly) does nothing. None of the command's canExecute() methods are called. The methods are being called when first binding to the commands but we can't call them after that :-/

Expose non-platform specific binding infrastructure as part of MvvmLightLibs

Hi,

In our .NET Standard core project, that's referenced by the platform specific projects we want to implement observation between the model and the view model.

We made our model classes extend ObservableObject, but there's no friendly way to observe the changes without implementing the event handler exposed by INotifyPropertyChanged ourselves.

Using the binding infrastructure that's available in the iOS and Android projects would make that much easier.

However the Binding class and the related extensions are not exposed in the MvvmLightLibs as well.

What do you think about this? Is there any other approach you would suggest for observing the model from the view models?

Thank you,
Cosmin

SimpleIoc.GetInstanceWithoutCaching returns same instance

Hello,
currently I've seen that GetInstanceWithoutCaching of SimpleIoc returns the same instance like GetInstance in some circumstances. I think GetInstanceWithoutCaching could always return a fresh instance regardless GetInstance was called before or not. See short unit test to enforce this behavior:


        [TestMethod]
        public void GetInstanceWithoutCachingReturnsSameInstanceWhenGetInstanceCalledBefore()
        {
            // Arrange
            var sut = new SimpleIoc();
            sut.Register<IMessenger, Messenger>();

            var notExpected = sut.GetInstance<IMessenger>();

            // Act
            var actual = sut.GetInstanceWithoutCaching<IMessenger>();

            // Assert
            Assert.AreNotEqual(notExpected, actual);
        }

I'm not sure if it is a bug or a feature.
Regards,
Steffen

Binding<double, string> fails with complex path with null member

Found the following issue with Bindings with complex paths: If you set a Binding<double, string> with a complex path, setting the binding fails because of a cast error from double to string, if one member of the complex path is null.
For example (if Btc is null):

_bindings.Add(this.SetBinding(
                () => Vm.Btc.Model.CurrentValue,
                () => ValueLabelBtc.Text));

DialogService need help

on android i get error when i try to showMessage
--- End of managed Java.Lang.NullPointerException stack trace ---
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:224)
at android.app.AlertDialog$Builder.(AlertDialog.java:454)
at md58432a647068b097f9637064b8985a5e0.ButtonRenderer_ButtonClickListener.n_onClick(Native Method)
at md58432a647068b097f9637064b8985a5e0.ButtonRenderer_ButtonClickListener.onClick(ButtonRenderer_ButtonClickListener.java:30)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

thanks

Add binding-redirects or other compatibility with CommonServiceLocator 1.4 or 2.0

The CommonServiceLocator package, upon which MvvmLight takes a dependency, was updated to version 1.4 and 2.0.1 (there was no 2.0.0 version) last month: https://www.nuget.org/packages/CommonServiceLocator/

My current project which uses the latest MvvmLight package (5.3.0) is unable to build with either the 1.4 or 2.0.1.

With version 1.4, VS2017 tells me I must continue to reference version 1.3.0 specifically:

The type 'IServiceLocator' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.Practices.ServiceLocation, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

As a quick-fix, is this something that could be resolved with a binding redirect?

Alternatively, the NuGet dependencies could be restricted to be exactly == 1.3.0.0 instead of the current >= 1.3.0, so NuGet won't upgrade to 1.4.0 or 2.0.1.

With version 2.0, the internal layout of the CommonServiceLocator library is significantly overhauled and namespaces have been renamed, breaking both the assembly reference, but also type resolution.

Would it be possible to remove the dependency on CommonServiceLocator entirely? I'm not familiar with MvvmLight's internals, but doing so would help, methinks.

[Android] Command binding throws System.InvalidCastException

Platform: Android
Version: GalaSoft.MvvmLight.Platform, Version=5.4.1.0

Pseudo-Code for Bug Description

Query = root.FindViewById<SearchView>(Resource.Id.search);
Query.SetCommand<QueryTextSubmitEventArgs>("QueryTextSubmit", ViewModel.TestCMD);

This throws always System.InvalidCastException: Specified cast is not valid.

I also tried other overloads and combinations result is Always the same

netstandard 2

Bonjour du Quebec!

Quick question - can we expect netstandard 2 compliance with next release ? it would fix one warning my clients get out of this package and put of source of doubts (when problems arise) away...

Severity Code Description Project File Line Suppression State
Warning NU1701 Package 'MvvmLightLibs 5.3.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETStandard,Version=v2.0'. This package may not be fully compatible with your project. ToDoStudio C:\Users\erikr\Source\Repos\TodoStudio\ToDoStudio\ToDoStudio\ToDoStudio.csproj 1

Problem with ListView binding

Hello,

I write a tool with mvvm light, my MainForm xaml code contains a ListView like this:

<ListView AlternationCount="2" ScrollViewer.CanContentScroll="True" ScrollViewer.HorizontalScrollBarVisibility="Auto" ItemsSource="{Binding SQLVersionenView, Mode=TwoWay}" MinHeight="25" Grid.ColumnSpan="2" Grid.Row="1">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="State">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <CheckBox IsChecked="{Binding import, Mode=TwoWay}"/>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
            <GridViewColumn Header="Version" DisplayMemberBinding="{Binding SQL_VERSION}"/>
            <GridViewColumn Header="comment" DisplayMemberBinding="{Binding COMMENT}"/>
            <GridViewColumn Header="path" DisplayMemberBinding="{Binding sql_path}"/>
        </GridView>
    </ListView.View>
</ListView>

The binding works pretty well, but I implemented a select all function and this don’t do anything

private void selectAllPretty() {
    foreach (SQLVersionInfo tmpSQLVersionInfo in SQLVersionenView) {
        tmpSQLVersionInfo.import = true; // Just update the value
    }
}

So I tried a little bit and found a way to get the job done:

private void selectAllUgly() {
    List<SQLVersionInfo> tmpSQLVersionenView = new List<SQLVersionInfo>(); // Create new list
    foreach (SQLVersionInfo tmpSQLVersionInfo in SQLVersionenView) {
        tmpSQLVersionInfo.import = true;
        tmpSQLVersionenView.Add(tmpSQLVersionInfo); // Fill the new list
    }
    SQLVersionenView = tmpSQLVersionenView; // Update the actual list
}

So my question is, is there a third way? What have I done wrong?

Best,
sonnenschein123

Can I see ALL messages being sent with MvvmLight?

I have a WPF application that uses MvvmLight. Messages are sent around at various points, and I would like to see (for debugging purposes, not for production code) whenever a message is sent, irrespective of where it originated.

Is this possible? I realise that I could pull down the source code for the library, use that instead of the actual DLLs, and set some breakpoints or similar, but that would be a huge amount of work. I'm hoping there is an easier way.

Thanks

Issues with CommonServiceLocator >2.0.2

I've just updated the MVVM Nuget to v5.4.1.

In the process the new CommonServiceLocator was updated to 2.0.2. All that went fine.
But there is now a 2.0.3 of CommonServiceLocator available. When updating to that version the app doesn't run anymore throwing this:

System.IO.FileNotFoundException: Could not load file or assembly 'CommonServiceLocator, Version=2.0.2.0

So I guess, despite the Nuget dependency mentioning CommonServiceLocator (>= 2.0.2) the package it's not actually that happy when using something above 2.0.2...

Android Navigation Memory Leak

Hello @lbugnion

I have been working through some performance issues with our MVVM Light app and noticed that the Heap Size seems to forever increase in Android. At first I assumed that this was an issue in our implementation of the MVVM Light architecture, but after doing some testing with the NavigrationDroid.sln, from MVVM Light Navigation Sample I suspect that the issue may lie within the MVVM Light framework.

When debugging the sample application above, the Heap Size starts around 10MB. From there the Heap Size will increase with each click of "Navigate to Page 2 with Parameter" and "Go back to Page 2". I am bench marking these values using the DDMS tool provided with Visual Studio 2015. I also had a colleague verify similar results using a Xamarin profiler with Visual Studio 2017.

Here is the Heap from DDMS when the NavigrationDroid.sln app is first deployed to a Motorola G5 phone.
image

After clicking through the navigation buttons for 1 minute (roughly 90 clicks) and clicked "Cause GC" within DDMS, here is the Heap:
image

Next I let the app rest for 1 minute, and proceeded with the same test. I clicked the navigation buttons for 1 minute (roughly 90 clicks) and clicked "Cause GC" within DDMS, here is the heap:
image

Would you have any idea about what is causing the Heap Size to continue to grow? I have been experimenting with unbinding the click events for each button using the OnStop/OnResume methods in Android but have not had much luck. Any advice or insight into this issue is greatly appreciated!

Thanks,

Bill

Proposal: Include essential, but missing, WPF/XAML functionality

I have my own little WPF utility library that provides some essential functionality that isn't included in WPF-proper (or other XAML frameworks, I assume) or MvvmLight. I'll be happy to share my implementation if you like. I think if they were included in the MvvmLight.Extras then they'd benefit more people.

I also have plans to build a Markup-Extension or Binding Converter that allows for C#-like expressions to be used in bindings, to eliminate the need for most Converters or hacks in ViewModels. Already there's the MathConverter available here: https://rachel53461.wordpress.com/2011/08/20/the-math-converter/ - but that's restricted to numeric arithmetic - but my proposal would use something like DLR/Dynamic-Linq or the built-in C# expression parser so we could do something like this:

I'm also looking at possibly avoiding common converters in Binding expressions by using better-typed Attached Properties, e.g.:

<Label mvvm:Vis.Visible="{Binding SomeBooleanProperty}"  />`

...where Vis.Visible is a Boolean property that proxies UIElement.Visibility, instead of:

<Resources>
    <BooleanToVisibilityConverter x:Key="boolToVis" />
</Resources>

<Label Visibility="{Binding SomeBooleanProperty, Converter={StaticResource boolToVis}}" />

Crash when using GetRecyclerAdapter extension method only when building on Mac.

Hello,

I noticed we got a crash when using the extension method "GetRecyclerAdapter" of https://www.nuget.org/packages/MvvmLightAndroidSupport/ when building app on Mac only.

Here the few lines that cause de crash :

var adapter = ViewModel.SettingsIntemViewModels.ToList().GetRecyclerAdapter(BindViewHolderDelegate, CreateViewHolder);

Here is a small tutorial I followed : http://www.blogaboutxamarin.com/using-the-mvvm-light-observablerecyleradapter-with-the-xamarin-android-recylerview/

We use the last version of Visual Studio for Mac and compile in Android 8.0 Oreo.
Unfortunately, I got no exception so I can't see what's wrong.

ViewModel folder and ViewModelLocator missing post nuget install

After creating a new Xamarin Forms 3.0 app in VS2017 I add MVVMLight 5.4.1 via NuGet the ViewModels folder and ViewModelLocator are missing from the project once nugget has completed.

How do I correct this? Is it something I have done or do I need to downgrade my version of MVVMLight?

Messang

Having an issue with Messanenger. Registering an event like

Messenger.Default.Register(this, e => Dispatcher.Invoke(Close))

in a child class of System.Windows.Window, and sending the event from a view model class of the window, but not closing. If I change the lambda to be a method, i.e.

Messenger.Default.Register(this, e => Dispatcher.Invoke(Close))
private void OnEventRcved(MyEvent e)
{
Dispacther.Invoke(Close);
}

It works. I was using ver. 5.3.0 and updated to 5.4.1, then 5.4.1.1 but still same. Call Register<>() in other parts with lambda and seems fine, so anything to do with Dispatcher?

Async RelayCommand

Would it be possible to have an async RelayCommand as part of this toolkit?

Designtime Exception when mixing .NET Standard project libraries with WPF .NET Framework application

I've discovered a potential bug when mixing .NET Standard library projects with a .NET Framework WPF project.

Scenario

Two projects:

  • .NET Standard class library project (targeting .Net Standard 2.0)
    • No other dependencies or implementations. Just an empty project.
  • WPF Front end project (targeting .NET 4.7)
    • References the above .NET standard project
    • Nuget package management format set to 'PackageReference'
    • References nuget package: MvvmLightLibs

Symptoms

The app runs as expected at runtime, but during design time a FileLoadException is thrown whenever ViewModelBase.IsInDesignModeStatic is called:

image

NOTE: this exception does not show up immediately on the first build, but usually kicks in once VS has been restarted - or 'Disable Project Code' is toggled in the XAML editor.

Source of the error

The exception is being thrown within the GetCurrentPlatform() of the Designer Library (Line 47)

Steps to reproduce

MvvmLightDesignModeBug.zip

This simple project implements the bare minimum to reproduce the error. Note that on first build the designtime view may appear to work. Try toggling the Disable Project Code button on and off:
image

Notes

This exception appears whether using the MvvmLightLibs or MvvmLightLibsStd10 packages.

Removing the WPF project's reference to the .NET standard class library will fix this error.

Potential Fix

Wrapping the calls to Type.GetType() in the DesignerLibrary with a try-catch so that failures here fall through.

UPDATE: Pull request #42 submitted.

Provide a way to remove a command

Hello,

Currently the SetCommand extension returns void.

This means that you can never detach a command.

This can turn into issues when you're using reusable cells (in a UITableView or a RecyclerView) where if you call SetCommand when the cell is configured with the view model, you'll get the same even to be triggered in multiple places.

One suggestion would be to have SetCommand return some kind of EventToCommandInfo that can expose a Detach method.

Thank you,
Cosmin

RelayCommand with Parameter canExecute not working

I just came across this issue with RelayCommand when supplying a parameter via RelayCommand<>(), it appears that the CanExecute method is never called. When setting breakpoints on both the CanExecute method below, only the RelayCommand without a parameter's CanExecute method is ever called, the breakpoint on the second method is never called.

tested with MvvmLightLibs 5.4.1 and 5.3.0 with same results

View Model

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;

public class MainWindowViewModel : ViewModelBase
{
    public ObservableCollection<string> Items { get; set; }

    private string _selectedItem;
    public string SelectedItem { get => _selectedItem; set => Set(ref _selectedItem, value); }

    public ICommand ParameterTestCmd { get; }
    public ICommand NoParameterTestCmd { get; }

    public MainWindowViewModel()
    {
        Items = new ObservableCollection<string>()
        {
            "test1",
            "test2",
            "test3"
        };

        NoParameterTestCmd = new RelayCommand(NoParameterTest, NoParameterTestCanExec);
        ParameterTestCmd = new RelayCommand<IList<string>>(ParameterTest, ParameterTestCanExec);
    }

    private void ParameterTest(IList<string> values)
    {
           
    }

    private bool ParameterTestCanExec(IList<string> values)
    {
        return values.Count > 0;
    }

    private void NoParameterTest()
    {

    }
    private bool NoParameterTestCanExec()
    {
        return SelectedItem != null;
    }
}

XAML

<Window x:Class="RelayCommandBugTest.MainWindow"
        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"
        xmlns:local="clr-namespace:RelayCommandBugTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <ListView x:Name="List" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}"/>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <Button Content="Parameter Test" CommandParameter="{Binding ElementName=List, Path=SelectedItems}" Command="{Binding ParameterTestCmd}"/>
        <Button Content="No Parameter Test" Command="{Binding NoParameterTestCmd}"/>
    </StackPanel>
</Window>

Code Behind

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainWindowViewModel();
    }
}

ObservableRecyclerAdapter crashes when datasource is changed outside of Ui thread

Hi!

I am using the ObservableRecyclerAdapter to bind my view against an ObservableCollection in my ViewModel.
When I am updating the collection inside of my view model my code crashes and tells my that I have to do the changes on the UI Thread.

How can i do that? Or better question, what method do I need to invoke?

Currently I am invoking all methods to setup the ObservableRecyclerAdapter and the BindViewHolder method, but no success till now.

Thx for your help!

PS. using async/await pattern is not an option.

SimpleIoc.Register does not enforce generic type TClass: TInterface constraint

SimpleIoc.Register<TInterface,TClass> does not have the generic type constraint that TClass : TInterface.

So you can do this:

class IFoo { }
class Foo : IFoo { }
class Bar {}

SimpleIoc.Register<IFoo,Bar>();

...and you won't get a compiler error, but it will crash at runtime.

I noticed that the Register<TInterface,TClass> method does have where TInterface : class where TClass : class as a constraint, so I suspect this isn't a simple oversight. Is there a reason it doesn't have a TClass : TInterface constraint?

Suggestion: split out MvvmLightCore out of MvvmLightLibs

What about splitting main library into separate nuget (e.g. MvvmLightCore) from extras? It feels like it's going to be pretty easy to make that one Standard 1.0, and current MvvmLight can have that one as dependency. Not sure about common usage profile, but project I'm trying to figure out at the moment doesn't use any Extras, still have to carry reference for CommonServiceLocator, System.Windows.Ineractivity and Extras itself. All of that staff was shipped along with app, even that it wasn't actually used anywhere.

Memory leak caused by the `Text` property

I am extending a debugger and I need to open mutliple source code editor instances in external windows. Furthermore, correct disposal is an absolute necessity. However, the following line causes a memory leak resulting in the view not being disposed, whereas the view model is:

<TextBox  Grid.Row="0" Grid.Column="1" Text="{Binding MyBinding, Mode=OneWayToSource}" MinWidth="20"></TextBox>

The setup is a little bit special, admittedly: the Text binding occurs in a MVVM window, which is created using the following code (for better understanding, I created a sketch):

// Launcher
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
    if (this.mvvmWindow != null)
    {
        this.mvvmWindow.Close();
    }

    this.mvvmWindow = new MVVMWindow();
    this.mvvmWindow.Closed += this.CleanupMVVMWindow;
    this.mvvmWindow.Show();
}

private void CleanupMVVMWindow(Object sender, EventArgs e)
{
    this.mvvmWindow.Closed -= this.CleanupMVVMWindow;
    this.mvvmWindow = null;

    GC.Collect();
    GC.WaitForFullGCComplete();
}

For debugging this behaviour I have created an example application with exactly that memory leak. Just run the application in a profiler like dotMemory and you'll see that the view stays alive after closing the window.

Data binding wouldn't work if the viewModel property value is been set inside a subscribed method

I'm using MvvmLightLibsStd10 (v5.4.1) package in a NetStandard 2.0 project and a Xamarin.IOs project. I also use Akavache (v6.0.0-alpha0038) package in these projects as well.

The issue is, when a bound property value is been set inside the subscribe method of Akavache's GetAndFetchLatest() method, the binding wouldn't invoke the view end property. (It would invoke if not been set from the subscribe method)

Details in code,

Inside HomeView:

private UILabel _label;

// label is created...

public string ViewProperty
{
    get => _label.Text;
    set => _label.Text = value;
}

Inside ViewController:

private readonly List<Binding> _bindings = new List<Binding>();

// in a method
_bindings.Add( this.SetBinding(() => _homeViewModel.ModelProperty, () => _homeView.ViewProperty) );

Inside HomeViewModel:

private string _text = "Initial";

public string ModelProperty
{
    get => _text;
    set => Set(ref _text, value);
}

// in a method
BlobCache.InMemory.GetAndFetchLatest(
    "theIdentifier",
    async () => await _homeService.GetString(),
    offset => true, null)
    .Subscribe(
        results =>
        {
            ModelProperty = results;
        });

The ModelProperty value been set inside Subscribe is not updating ViewProperty value.

Updated NuGet Packages?

It appears there is still active development on mvvmlight (according to the commits) but on nuget there was no update since 4/27/2016. Can we expect any update soon? Already an update which brings all dependencies to the latest versions would already be great. It still refers to CommonServiceLocator 1.3.0 which has a different namespace.

Messenger strange behavior [BUG]

I have a relatively small application here. Here is the code snippet from my constructor:
image

You can find the whole class here.

The problem is that the registration callback at line 58 will be executed and the callback at 62 not. The registration is exactly the same. If I switch the registrations or remove the first one the result is still the same... Somehow never going to hit the callback at line 62.

Do you have some suggestions for me? Do I miss something?

Thank you

VerifyPropertyName in UWP

Hi,

We are currently working on UWP application and we have found an issue that you have already fixed. The issue in question is: 7d400cf.

So, I was wondering when will you release new version with this fix on NuGet?

Update canExecute

Hello,
to dis-/enable a button I use the RelayCommand with the canExecute parameter.
My problem is, in case the window is not focused, the buttons are not gone updated. If I focus the Window everything works fine.
I tried to call the RaiseCanExecuteChanged and set keepTargetAlive true, but it wont work.
Where is the missing link? how can I execute the function correctly?

Best,
Sonnenschein123

Warning under Xamarin.Forms project

Hi,

I created a dummy app in .NET 2017 Community Edition, added MVVMLight Nuget package at the at solution level and selected all projects (.NET standard, iOS, Android and UWP) and while it installed successfully, I somehow could not access Galasoft or MvvmLight namespaces in the project.

I ended up removing it and adding MVVMLightLibs Nuget package instead and it seems that with this one I was able to access the Galasoft & MvvmLight namespaces and while everything so far appears to be ok, I'm still getting a warning:

Severity Code Description Project File Line Suppression State
Warning NU1701 Package 'MvvmLightLibs 5.4.1.1' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETStandard,Version=v2.0'. This package may not be fully compatible with your project. XamarinForms101 C:\Users\User\source\repos\XamarinForms101\XamarinForms101\XamarinForms101\XamarinForms101.csproj 1

Any ideas?

Thanks.

T.

PS: I haven't replaced the ServiceLocator just yet but if I recall one of your articles, I think this was removed. Is there a full example using the latest version of Xamarin Forms & MVVMLight that at least highlights how to get around the fact there isn't a ServiceLocator, on how to use RelayCommand, EventToCommand, Messenger, etc.... Thanks. T

Microsoft.Practices.ServiceLocation changed to CommonServiceLocator

I don't know if this is a real issue or not, since I am completely new to mvvmlight.

The New Project template references Microsoft.Practices.ServiceLocation whereas the updated CommonServiceLocator assembly is called just that. It appears that the assembly was renamed for version 2.0.0+?

Can the New Project template for mvvmlight be updated to reflect this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.