Giter Site home page Giter Site logo

mvvm-samples's Introduction

Community Toolkit Docs

This repo contains the guidance documentation for various Community Toolkits that are part of the .NET Foundation.

This includes the following projects:

  • .NET Community Toolkit (and MVVM Toolkit)
  • .NET MAUI Community Toolkit
  • Windows Community Toolkit (though our docs are still migrating from the old repo here)

More information to come...

Microsoft Open Source Code of Conduct

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

mvvm-samples's People

Contributors

azchohfi avatar denis-tsv avatar jamesmcroft avatar kazo0 avatar michael-hawker avatar mrlacey avatar niels9001 avatar sergio0694 avatar sinantutan 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

mvvm-samples's Issues

Avalonia Sample

Following from my comment in #8.
I'd like to create a sample project for Avalonia.

Navigation sample

It would be great to have a sample focusing on navigation between pages, showing how to pass data between them, how to create the ViewModels using IoC and wiring up the ViewModels with the page views the user is navigating to.

Compile Errors: The type or namespace name 'ICommand' could not be found

I have tried upgrading my NuGet for the Community Toolkit.Mvvm the last 2 times that an update was available (Preview 4 and 8.0.0 Stable).
Both times, I started getting compile errors as described in the title of this issue.
So, I have had to revert back to version 8.0.0-preview3, which still compiles and runs cleanly.

Any help in getting past this would be appreciated!

[feature] Fontscaling in Shell.xaml for better readability on high Resolution Screens.

Hi. I´m so confident this is a nice MVVM Toolkit. Nice work.

Back to the Topic: Feature request is simple.

It would be nice to have a Scaling option.
I am getting old and my 4k Screen is nice to have, but to have to read in the UWP Sample app is really hard.
I added this to the Shell.xaml in the muxc:NavigationViewItems at the end.

<muxc:NavigationViewItemSeparator />
<muxc:NavigationViewItem>
    <StackPanel Orientation="Horizontal">
        <TextBlock
            Margin="0,0,7,0"
            VerticalAlignment="Center"
            Text="FontSize" />
        <muxc:NumberBox
            HorizontalAlignment="Left"
            Maximum="72.0"
            Minimum="8.0"
            PlaceholderText=""
            Value="{x:Bind FontSize, FallbackValue=14.0, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
        <TextBlock
            Margin="7,0,0,0"
            VerticalAlignment="Center"
            FontStyle="Italic"
            Text="from 8 to 72 - decimal" />
    </StackPanel>
</muxc:NavigationViewItem>     

grafik

grafik

I would made a change in the Repo and maybe a MergeRequest, but I am new to Git.
I dont´wnt to mess up things. :)

Thank You in advance if FontScaling could be implemented.

Greetings from Hamburg, Germany.
Zui.

How to Implement Interface when using ObservableProperty & RelayCommand attributes?

Hello,

Is there a sample showing how to implement an interface when using ObservableProperty & RelayCommand attributes? How would one implement the ISampleViewModel interface for SampleViewModel?

public partial class SampleViewModel : ObservableObject
{
[ObservableProperty]
ObservableCollection items;

[RelayCommand]
void IncrementCounter()
{
}

}

public interface ISampleViewModel
{
ObservableCollection Items { get; set; }

void IncrementCounterCommand();

}

Other Samples?

Does it make sense to have additional samples?

  • Avolonia
  • Blazor
  • WinForms?

If so, we can create additional issues for these.

Any other suggestions?

Navigating to another window under WPF?

As far as I can tell, the kit does not seem provide some abstract infrastructure on how to achieve that.

Say I have a main window, i.e. the shell and I'd like to open another window, not a user control that would sit in a frame in the shell.

How would you achieve that?

MVVM Toolkit Sample App - Reddit Service example wrongly uses IOC class

In the samples app, in the Putting Things Together section, the example follows a process whereby services are created, registered in the app.xaml.cs and then injected into the viewmodels via constructor injection.

On the Reddit Service example the SubredditWidgetViewModel gets the IRedditService from the IOC.Default instance

/// <summary>
/// Gets the <see cref="IRedditService"/> instance to use.
/// </summary>
private readonly IRedditService RedditService = Ioc.Default.GetRequiredService<IRedditService

The rest of the sample app doesnt mention really the IoC class at all, and the service is definitely not registered with it in the examples. In fact further down its registered in the app.xaml.cs.

This example should be reworked slightly to accept the IRedditService via constructor injection, like the PostWidgetViewModel.
Similarly, the SubredditWidgetViewModel should also be shown to be registered with the service collection too, for consistency

Docs - Services in "Putting things together"

The Putting things together page describes how to make and implement services, but it doesn't explain how to use them. The Building the UI section gives a sample, but it doesn't work.

  1. App.Current doesn't have a Services property. I discovered in #22 that you have to cast it like this ((App)Application.Current).Services to access it.
  2. The code included at the end of the previous section doesn't seem to set the Services property. When I tried the above fix in the constructor of my MainPage, Services was null.
  3. IServiceProvider doesn't have a GetService<T>() method in the latest version of Microsoft.Extensions.DependencyInjection (5.0.0). It seems to have been changed to GetService(Type serviceType).

Base PageViewModel and PageView

Create BasePageViewModel with methods OnActivated/OnDeactivated (or OnNavigatedTo/OnNavigatefFrom) and PasePage. Invoce corresponding methods of PageViewModel on Page lifecycle.
It will allow to move LoadDocsCommand from xaml.cs file to PageViewModel.OnActivated. So we will keep codebehind file empty

Async validation sample

Love the Idea of having only this toolkit without external dependencies.
Would you give an example of doing async validation.

Load Async data in a UserControl with SetPropertyAndNotifyOnCompletion instead of NotifyTaskCompletion

Hello,

I'm currently modifying a UserControl to remove NotifyTaskCompletion class and use directly the Task with SetPropertyAndNotifyOnCompletion .

I am working on a .NET 4.8 project in WPF and I have the following problem:
Constructor

public ArticleCategoryUserControlModel()
        {
            _serviceProvider = ApplicationBootstrapper.ServiceProvider;

            AllArticleCategoriesTask = RequestValuesAsync();
        }
private async Task<ObservableCollection<IArticleCategoryBusinessModel>> RequestValuesAsync()
        {
            using var scope = _serviceProvider.CreateScope();
            var articleCategoryReader = scope.ServiceProvider.GetRequiredService<IArticleCategoryReader>();
            await Task.Delay(3000); // for debug purpose
            var res = await articleCategoryReader.GetAllAsync();
            return new ObservableCollection<IArticleCategoryBusinessModel>(res);
        }

Currently I am still using the following result wrapper:

public ObservableCollection<IArticleCategoryBusinessModel> AllArticleCategoriesResult =>
            AllArticleCategoriesTask.Status == TaskStatus.RanToCompletion
            ? AllArticleCategoriesTask.Result
            : null;

Corresponding Xaml

<Grid Visibility="{Binding AllArticleCategoriesTask.IsCompleted, Converter={StaticResource BooleanToVisibilityFbConverter}}" 
           Background="Pink">
            <dxe:ComboBoxEdit ItemsSource="{Binding AllArticleCategoriesResult}">
            <dxe:ComboBoxEdit.StyleSettings>
                <dxe:TokenComboBoxStyleSettings />
            </dxe:ComboBoxEdit.StyleSettings>
        </dxe:ComboBoxEdit>
</Grid>

My question is the following: Is it possible to do the same behavior without the AllArticleCategoriesResult property?

In the Xaml, I can't directly use AllArticleCategories.Result because it causes me to freeze the UI. I have to use the AllArticleCategoriesResult property.

Thanks

Xamarin Android Native

Hi!
I'm evaluating MVVM frameworks for use in a xamarin android application. MVVMLight says they recommend your implementation, but it doesn't seem to directly support xamarin android native. Do you recommend still using MVVMLight in my case ?
Thanks!

WPF Samples

Anyone have a simple WPF (full framework) sample working with the MVVM toolkit? I've tried following the docs, but not having much luck.

Designer is not loading saying build is needed to load, unable to cast object of type "WpfSurfaceApp". Binding a TextBlock and Button and appear to run/work, but designer is not happy.

Prob something I'm doing wrong. Thx

Unable to build Samples

Error occurred while restoring NuGet packages: Unable to load the service index for source https://pkgs.dev.azure.com/dotnet/WindowsCommunityToolkit/_packaging/WindowsCommunityToolkit-MainLatest/nuget/v3/index.json

While attempting to build the UWP project, a notification to login to my microsoftt account pop-ups repeatedly and eventually fails with this error message. It appears that the packagemanager is referring to a CI package manager that I don't have access to. Please advice.

Different viewmodels instances of same type

Hi.

Should I use, say, 2 instances of same viewmodel in 2 different views (e.g. side-by-side panels), how could I initialize such viewmodels properly (e.g. passing "left" and "right" context/initialization argument to each viewmodel)?

Thanks.

Usage of view models in XAML Designer in Visual Studio or Blend

Ask:

It would be great to see a recommended approach for

  • how to use the view models in the XAML Designer (in Visual Studio or Blend).
  • best practices around switching between real view models/ services and view models containing sample data

Rationale:

The XAML Designer does not automatically load C# code. E.g. if you register your viewmodels with dependency injection (which you make available through a property on App and in your codebehind you write this.DataContext = ((App)Application.Current).Services.GetService<MyFancyViewModel>(); then the XAML designer will not be able to load it.

The Blend / the XAML designer can only load objects with a default (parameterless) constructor that are initialized in XAML itself, e.g.

<Page.DataContext>
   <vm:MyViewModel x:Name="ViewModel" />
</Page.DataContext>

One suggested solution to this (which MVVMLight did) was the use of the ViewModelLocator pattern - which you could include in your XAML and which would construct the viewmodel for you.

Some relevant links:

Handling an IAsyncRelayCommand in WinUI 3.0

in issue #5 it mentions that the UWP example can be used to also do WinUI 3.0 by using CommunityToolkit.MVVM.

In the example for handling an IAsyncRelayCommand looks to be using Microsft.Toolkit.Uwp.UI.Converters in AsyncRelayCommandPage.xaml to get the task result.

My question is how should one get a task result in WinUI 3.0? I would guess there is a non-UWP specific converter that should be used, but I am not sure what it is and haven't been able to find it.

Docs - Add Migration Guide for NotifyTaskCompletion

As part of CommunityToolkit/WindowsCommunityToolkit#3435, we're removing the NotifyTaskCompletion helper from the Toolkit. We should have a section in the docs for AsyncRelayCommand on how to migrate code from that pattern to this one.

Or maybe it's in ObservableObject. Both places may want to call something out, maybe they both link to a separate page?

Just want to make sure we show folks that used NotifyTaskCompletion in C#/XAML how to convert that over with the full C#/XAML pattern in old and new style shown.

Best practice to propagate property changes to parent class

Hello everyone,
I'm pretty new to this very promising MVVM toolkit,
I wish to know if there's an already easy to use built in mechanism for propertychanged notification between classes.
Please provide a small example useful for everyone, expoecially for beginners like me.

Thank you in advance!

The scenario:

//The "parent" class
public class Person: ObservableValidator
{
   private string _name;
   public string Name { get => _name; set { SetProperty(ref _name, value); } }

  private List<Address>  _addresses;
  public List<Address>  Addresses 
  { 
    get => _addresses; 
    set 
       { 
             SetProperty(ref _addresses, value);
                   
                   //I need here  to  call  a method  when **Address.IsDefault**  has changed in any Address of the list
        }
    }
//other properties here........
}


//The "child "class used as property (a List) in the parent class

public class Address: ObservableValidator
{
   private bool  _isDefault;
   public bool  IsDefault { 
     get => _isDefault; 
     set {
              SetProperty(ref _isDefault, value); 
             // I need here to notify the "parent" class (Person) that  _isDefault has changed
           } 
    }

  private string  _fullAddress;
  public string   FullAddress{ get => _fullAddress; set { SetProperty(ref _fullAddress, value); } }

//other properties here........
}

RelayCommand disables the button

Creating a dynamic buttons in code behind makes the button disabled when the RelayCommand is used.
Here is a example

        var removeButton = new Button()
        {
            Content = "X",
            Command = new RelayCommand<int>(RemoveEntry),
            CommandParameter = index,
        };

then afterwards adding this button to a StackPanel the property isEnabled is always false (no matter how it's bound).

There is a workaround solution make it work
First object initialize the button with IsEnabled =true, without setting the command

        var removeButton = new Button()
        {
            Content = "X",
            IsEnabled = true,
            CommandParameter = index,
        };

afterwards just set the command

        removeButton.Command = new RelayCommand<int>(RemoveEntry);

WPF Command CanExecute Sample

Anyone have examples how to use ICommand and CanExecute using WPF? I thought I came across some mentions you must add more in addition to what is provided with the MVVM toolkit.

Any help is appreciated.

Sample App Design/Outline

What should our sample apps look like?

We should have a consistent implementation across all our platform implementations.

This could be either a simple guidebook app which shows feature in isolation OR a showcase type app which is more of a 'complete' app which shows things together.

If we do one type of app for all our platforms, we should at least do the opposite for one platform like UWP.

OnActivated and OnDeactivated not working on ObservableRecipient

I've been testing ObservableRecipient in a WPF application and want to use OnActivated and OnDeactivated explicitly. However it's not working for me, I've produced basic simple reproducible project and it's still not working, OnActivated and OnDeactivated are not firing. Am I missing something obvious or is this a bug?

WpfApp1.csproj:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net5.0-windows</TargetFramework>
    <UseWPF>true</UseWPF>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Toolkit.Mvvm" Version="7.0.0-preview4" />
  </ItemGroup>

</Project>

App.xaml:

<Application x:Class="WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp1"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
         
    </Application.Resources>
</Application>

App.xaml.cs:

using System.Windows;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
    }
}

MainViewModel.cs:

using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Messaging;
using System.Diagnostics;

namespace WpfApp1
{
    public class MainViewModel : ObservableRecipient
    {
        public MainViewModel()
        {

        }

        protected override void OnActivated()
        {
           // Not firing
            Debug.WriteLine("OnActivated()");
            Messenger.Register<MainViewModel, MessageForMainViewModel>(this, (r, m) => r.Receive(m));
        }

        protected override void OnDeactivated()
        {
           // Not firing
            Debug.WriteLine("OnDeactivated()");
        }

        public void Receive(MessageForMainViewModel message)
        {
            if(message.Message.Equals("Increment"))
            {
                Increment++;
            }
        }

        private int _increment;
        public int Increment
        {
            get => _increment;
            set => SetProperty(ref _increment, value);
        }
    }
}

MessageForMainViewModel.cs:

namespace WpfApp1
{
    public class MessageForMainViewModel
    {
        public string Message { get; }
        public string Method { get; }
        public MessageForMainViewModel(string method, string message)
        {
            Message = message;
            Method = method;
        }
    }
}

MainWindow.xaml:

<Window x:Class="WpfApp1.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:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel Orientation="Vertical">
            <TextBlock Text="{Binding Increment}"/>
            <Button Content="Increment" Click="Button_Click"/> 
        </StackPanel>
    </Grid>
</Window>

MainWindow.xaml.cs:

using Microsoft.Toolkit.Mvvm.Messaging;
using System.Windows;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private MainViewModel _mainViewModel;
        public MainWindow()
        {
            InitializeComponent();

            _mainViewModel = new MainViewModel();
            var active = _mainViewModel.IsActive;
            this.DataContext = _mainViewModel;

        }

        // Just a quick example, usually won't use control events like this
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            WeakReferenceMessenger.Default.Send(new MessageForMainViewModel("Increment", "Simple Test Message to Increment counter."));
        }
    }
}

Docs - Migration Guide from Caliburn.Micro

Caliburn.Micro will no longer be under active development in the future. We should provide some sort of guide for users coming from that framework to help transition.

If anyone has experience with that framework, please let us know if you'd be willing to help out with this guidance, thanks!

Null exception on Ioc.Default.ConfigureServices on Android after return from OnDestroy

System.InvalidOperationException: The default service provider has already been configured
at Microsoft.Toolkit.Mvvm.DependencyInjection.Ioc.ThrowInvalidOperationExceptionForRepeatedConfiguration () [0x00000] in //Microsoft.Toolkit.Mvvm/DependencyInjection/Ioc.cs:164
at Microsoft.Toolkit.Mvvm.DependencyInjection.Ioc.ConfigureServices (System.IServiceProvider serviceProvider) [0x0000f] in /
/Microsoft.Toolkit.Mvvm/DependencyInjection/Ioc.cs:139
at CSLightsMVVM.App..ctor () [0x00009] in C:\Users\Tom\source\repos\CSLightsMVVM\CSLightsMVVM\CSLightsMVVM\App.xaml.cs:29

The problem is that Ioc.Default object is instantiated itself and apparently not destroyed after MainActivity.OnDestroy() is called. Then, when user return app from stack, App ctor is run again and there no way to check if Ioc.Default had been already configured or not.

EventToCommand in this MVVM Toolkit

Hey!

We're migrating our WPF solution to core and noticed that the Galasoft MVVM Toolkit seems to have been superseded by this one. One problem that came up is how to express this kind of example ..

xmlns:cmd="clr-namespace:GalaSoft.MvvmLight;assembly=GalaSoft.MvvmLight"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
<!-- ... -->
<Border>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseLeftButtonDown">
            <i:InvokeCommandAction Command="{Binding ItemSelectedCommand}" CommandParameter="{Binding}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Border>

in this new framework. There is a sample in the docs that uses a interactions namespace but never explains where this namespace comes from (probably it's not even WPF). Also there doesn't seem to be a WPF sample app.

Is WPF even supported? If so, how can we do this kind of thing?

Thanks!

MVVM Toolkit Sample App - Stance on IoC class

Im a bit confused about the sample apps stance on the Ioc class.
On the introduction page, the Ioc class is mentioned
image
However the rest of the app seems to deny its existence. For example, on the Inversion of Control page, its stated there that the toolkit provides no APIs to facilitate ioc or dependency injection or constructor injection (however does provide a link to the IOC class right below that, but then in the example below that it sets up the IServiceProvider in the app.xaml.cs and uses App.Current to get access to the service provider statically, rather than the Ioc class).
Similarly in the Settings Service page, it states "It is also possible to use other patterns, such as the service locator pattern, but the MVVM Toolkit does not offer built-in APIs to enable that.", but thats exactly what the IoC class does, it provides a mechanism almost solely to simplify the service locator pattern.

Dont get me wrong, i dont like the IoC class, personally, but im a bit confused on the mixed messaging here in the sample app.

Prebuilt demo app

I downloaded this app thinking It would be the content of this same repo. But it seems no.

Can you please upload a prebuilt binary? Or where can I get it?

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.