ICommand in MVVM WPF - c#

I'm having a look at this MVVM stuff and I'm facing a problem.
The situation is pretty simple.
I have the following code in my index.xaml page
<Grid>
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<view:MovieView ></view:MovieView>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
and in my index.xaml.cs
...
InitializeComponent();
base.DataContext = new MovieViewModel(ent.Movies.ToList());
....
and here is my MoveViewModel
public class MovieViewModel
{
readonly List<Movies> _m;
public ICommand TestCommand { get; set; }
public MovieViewModel(List<Movies> m)
{
this.TestCommand = new TestCommand(this);
_m = m;
}
public List<Movies> lm
{
get
{
return _m;
}
}
}
finally
here is my control xaml MovieView
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label VerticalAlignment="Center" Grid.Row="0" Grid.Column="0">Title :</Label><TextBlock VerticalAlignment="Center" Grid.Row="0" Grid.Column="1" Text="{Binding Title}"></TextBlock>
<Label VerticalAlignment="Center" Grid.Row="1" Grid.Column="0">Director :</Label><TextBlock VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" Text="{Binding Director}"></TextBlock>
<Button Grid.Row="2" Height="20" Command="{Binding Path=TestCommand}" Content="Edit" Margin="0,4,5,4" VerticalAlignment="Stretch" FontSize="10"/>
</Grid>
So the problem I have is that if I set ItemsSource at Binding
it doesn't make anything
if I set ItemsSource="{Binding lm}"
it populates my itemsControl but the Command (Command="{Binding Path=TestCommand}" ) doesn't not work.
Of course it doesn't not work because TestCommand doesn't not belong to my entity object Movies.
So finally my question is,
what do I need to pass to the ItemsControl to make it working?
Thx in advance

As soon as your items are rendered, each item gets set to the DataContext of the specific row it represents, so you are no longer able to reference to your first DataContext.. Also, due to the fact that you are in a DataTemplate, your bindings will start working when there is need for that Template.. so in that case you need to look up your parent control through a RelativeSource binding...
Hope that explains some things..

Try implementing the INotifyPropertyChanged interface:
public class MovieViewModel : INotifyPropertyChanged
{
readonly List<Movies> _m;
private ICommand _testCommand = null;
public ICommand TestCommand { get { return _testCommand; } set { _testCommand = value; NotifyPropertyChanged("TestCommand"); } }
public MovieViewModel(List<Movies> m)
{
this.TestCommand = new TestCommand(this);
_m = m;
}
public List<Movies> lm
{
get
{
return _m;
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string sProp)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(sProp));
}
}
}
What happens is that the TestCommand has a value, and the UI gets no notification that a change is taking place.. On controls you solve this problem using Dependency properties, on data object, you can use the INotifyPropertyChanged interface..
Secondly, the Movie objects have no reference to the parent object..
You can solve this problem in three different ways:
have a reference back to the model on Movie, and make the Bind path like so: ie.. if you property is named ParentMovieModel, then your Binding will be like:
{Binding Path=ParentMovieModel.TestCommand}
Make a binding based on ElementName like so: Seek up the parent control where you set your DataContext on, and give it a name: i.e. Root. Now create a binding based on the ElementName like so:
{Binding ElementName=Root, Path=DataContext.TextCommand}
Make a binding based on a RelativeSource like so: Seek up the parent control by type, and use the same path as the one above...
{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type yourparentwindowtype}}, Path=DataContext.TextCommand}

Got it working
here is the thing
<ItemsControl DataContext="{Binding}" ItemsSource="{Binding lm}">
Command="{Binding Path=DataContext.TestCommand, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"
so the RelativeSource was the thing I've missed.
if somebody has a good explaination of this, I would be definitely happy.

//include namespace
using Microsoft.Practices.Composite.Wpf.Commands;
readonly List<Movies> _m;
public ICommand TestCommand { get; set; }
public MovieViewModel(List<Movies> m)
{
this.TestCommand = new DelegateCommand<object>(TestcommandHandler);
_m = m;
}
public List<Movies> lm
{
get
{
return _m;
}
}
void TestcommandHandler(object obj)
{
// add your logic here
}
}

What about <ItemsControl ItemsSource="{Binding Path=lm}"> ?

in the ItemsSource="{Binding Path=lm}"> case
the itemsControl works well but I complety bypass my MovieViewModel
and I got this in the output window
System.Windows.Data Error: 39 : BindingExpression path error: 'TestCommand' property not found on 'object' ''Movies' (HashCode=1031007)'. BindingExpression:Path=TestCommand; DataItem='Movies' (HashCode=1031007); target element is 'Button' (Name=''); target property is 'Command' (type 'ICommand')
Movies is my entity object and owns only the Title and Director properties

Related

WPF Navigation while Keeping Menubar (Header) and Footer Fixed

We used to develop application with WinForms and nowadays we are trying to migrate it to WPF, starting from zero. In our application we have 3 main parts on screen which are Header (all main menu items), body (based on MDI container, content can be changed) and the footer (where general status is displayed, logo etc.) Whenever a user clicks on different menuitem from header part, the body part would change it's children to that Panel/Form.
There are lot's of good examples/tutorials on the Internet but I am confused about how to achieve to create a navigation service that allows to switch the view of body part.
Any suggestions would be appriciated, thanks in advance.
There are indeed multiple ways to archive this result. I will try and explain the very basic/easiest way to get the result.
While this will not provide example in combination with Menu Control, I think it will help you to understand the concept
In your MainWindow you can split use Grid layout and split the space into 3 parts as you wanted. Your Main window Xaml should look something like this :
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="*"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<ContentControl x:Name="Header"/>
<ContentControl x:Name="Content" Grid.Row="1/>
<ContentControl x:Name="Footer" Grid.Row="2"/>
</Grid>
In your content control you can insert your "UserControls" for the Header,Content,Footer. Now to the navigation part:
As mentioned there are many ways to archive this and I will describe what I do consider the easiest way (not the most flexible way however, so keep that in mind).
First I will suggest to make a navigation Model:
public class NavigationModel
{
public NavigationModel(string title, string description, Brush color)
{
Title = title;
Description = description;
Color = color;
}
public string Title { get; set; }
public string Description { get; set; }
public Brush Color { get; set; }
public override bool Equals(object obj)
{
return obj is NavigationModel model &&
Title == model.Title &&
Description == model.Description &&
Color == model.Color;
}
public override int GetHashCode()
{
return HashCode.Combine(Title, Description, Color);
}
}
We create a new class that will handle the navigation collection, lets call it navigation service.
public class NavigationService
{
public List<NavigationModel> NavigationOptions { get=>NavigationNameToUserControl.Keys.ToList(); }
public UserControl NavigateToModel(NavigationModel _navigationModel)
{
if (_navigationModel is null)
//Or throw exception
return null;
if (NavigationNameToUserControl.ContainsKey(_navigationModel))
{
return NavigationNameToUserControl[_navigationModel].Invoke();
}
//Ideally you should throw here Custom Exception
return null;
}
//Usage of the Func, provides each call new initialization of the view
//If you need initialized views, just remove the Func
//-------------------------------------------------------------------
//Readonly is used only for performance reasons
//Of course there is option to add the elements to the collection, if dynamic navigation mutation is needed
private readonly Dictionary<NavigationModel, Func<UserControl>> NavigationNameToUserControl = new Dictionary<NavigationModel, Func<UserControl>>
{
{ new NavigationModel("Navigate To A","This will navigate to the A View",Brushes.Aqua), ()=>{ return new View.ViewA(); } },
{ new NavigationModel("Navigate To B","This will navigate to the B View",Brushes.GreenYellow), ()=>{ return new View.ViewB(); } }
};
#region SingletonThreadSafe
private static readonly object Instancelock = new object();
private static NavigationService instance = null;
public static NavigationService GetInstance
{
get
{
if (instance == null)
{
lock (Instancelock)
{
if (instance == null)
{
instance = new NavigationService();
}
}
}
return instance;
}
}
#endregion
}
This service will provide us with action to receive desired UserControll (note that I am using UserControl instead of pages, since they provide more flexibility).
Not we create additional Converter, which we will bind into the xaml:
public class NavigationConverter : MarkupExtension, IValueConverter
{
private static NavigationConverter _converter = null;
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (_converter is null)
{
_converter = new NavigationConverter();
}
return _converter;
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
NavigationModel navigateTo = (NavigationModel)value;
NavigationService navigation = NavigationService.GetInstance;
if (navigateTo is null)
return null;
return navigation.NavigateToModel(navigateTo);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> null;
}
In our MainWindows.xaml add reference to the Converter namespace over xmlns, for example :
xmlns:Converter="clr-namespace:SimpleNavigation.Converter"
and create insance of converter :
<Window.Resources>
<Converter:NavigationConverter x:Key="NavigationConverter"/>
</Window.Resources>
Note that your project name will have different namespace
And set the Add datacontext to the instance of our Navigation Service:
You can do it over MainWindow.Xaml.CS or create a ViewModel if you are using MVVM
MainWindow.Xaml.CS:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = Service.NavigationService.GetInstance.NavigationOptions;
}
}
Now all is left to do is navigate. I do not know how about your UX, so I will just provide example from my github of the MainWindow.xaml. Hope you will manage to make the best of it :
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<StackPanel>
<ListView
x:Name="NavigationList"
ItemsSource="{Binding}">
<ListView.ItemTemplate>
<DataTemplate>
<Border
Height="35"
BorderBrush="Gray"
Background="{Binding Color}"
ToolTip="{Binding Description}"
BorderThickness="2">
<TextBlock
VerticalAlignment="Center"
FontWeight="DemiBold"
Margin="10"
Text="{Binding Title}" />
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
<ContentControl
Grid.Column="1"
Content="{Binding ElementName=NavigationList,Path=SelectedItem,Converter={StaticResource NavigationConverter}}"/>
</Grid>
Just in case I will leave you a link to github, so it will be easier for you
https://github.com/6demon89/Tutorials/blob/master/SimpleNavigation/MainWindow.xaml
Using same principle to use Menu Navigation
<Window.DataContext>
<VM:MainViewModel/>
</Window.DataContext>
<Window.Resources>
<Converter:NavigationConverter x:Key="NavigationConverter"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<Menu>
<MenuItem Header="Navigaiton"
ItemsSource="{Binding NavigationOptions}">
<MenuItem.ItemTemplate>
<DataTemplate>
<MenuItem
Command="{Binding DataContext.NavigateCommand, RelativeSource={RelativeSource AncestorType=Window}}"
CommandParameter="{Binding}"
Header="{Binding Title}"
Background="{Binding Color}"
ToolTip="{Binding Description}">
</MenuItem>
</DataTemplate>
</MenuItem.ItemTemplate>
</MenuItem>
</Menu>
<ContentControl
Grid.Row="1"
Background="Red"
BorderBrush="Gray"
BorderThickness="2"
Content="{Binding CurrentView,Converter={StaticResource NavigationConverter}}"/>
<Border Grid.Row="2" Background="{Binding CurrentView.Color}">
<TextBlock Text="{Binding CurrentView.Description}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</Grid>
And we have in VM List of the navigation Models, Current Model and the navigation command :
public class MainViewModel:INotifyPropertyChanged
{
public List<NavigationModel> NavigationOptions { get => NavigationService.GetInstance.NavigationOptions; }
private NavigationModel currentView;
public NavigationModel CurrentView
{
get { return currentView; }
set
{
currentView = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("CurrentView"));
}
}
RelayCommand _saveCommand;
public event PropertyChangedEventHandler PropertyChanged;
public ICommand NavigateCommand
{
get
{
if (_saveCommand == null)
{
_saveCommand = new RelayCommand(Navigate);
}
return _saveCommand;
}
}
private void Navigate(object param)
{
if(param is NavigationModel nav)
{
CurrentView = nav;
}
}
}
Sorry for long reply
I think that you not necessary have to start from scratch. You may have a look:
https://qube7.com/guides/navigation.html

How to link commands between user control and main in MVVM

I have a user control which have one TextBox and one Button called View. The TextBox takes index values.
On my Main view, I have one list view which will display all lines in a file.
An ObservableCollection is Bind to this.
What I need is, when index value is entered in the TextBox and View Button is clicked(in the user control), the SelecedIndex of the ListView(in the Main) should be changed to the index value.
How can I achieve this using MVVM?
Also, Please provide the proper approach to do this if I am doing it wrong.
Here is my UserControl Code:
XAML
<UserControl.DataContext>
<VM:IndexView_VM ></VM:IndexView_VM>
</UserControl.DataContext>
<Grid Background="White">
<TextBlock Margin="10,12,168,9" Text="Index : "/>
<TextBox Text="{Binding Index}" x:Name="TB_Index" Margin="53,11,90,8" />
<Button Command="{Binding View_CMD}" x:Name="BT_View" Content="View" Margin="136,11,10,8" />
</Grid>
ViewModel
public class IndexView_VM : ViewModelBase
{
public IndexView_VM()
{
View_CMD = new RelayCommand(_View_CMD);
}
int _Index;
public int Index
{
get { return _Index; }
set
{
_Index = value;
RaisePropertyChanged();
}
}
public RelayCommand View_CMD { get; set; }
internal void _View_CMD(object Parameter)
{
// What to write here?
}
}
Here is the Main View:
XAML
<UserControl.DataContext>
<VM:MainView_VM></VM:MainView_VM>
</UserControl.DataContext>
<Grid Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="111*"/>
<ColumnDefinition Width="100*"/>
</Grid.ColumnDefinitions>
<StackPanel>
<local:IndexView/>
<local:IndexView/>
<local:IndexView/>
<local:IndexView/>
</StackPanel>
<ListView ItemsSource="{Binding FileData}" x:Name="listView" Grid.Column="1" >
<ListView.View>
<GridView>
<GridViewColumn Header="Data" Width="100"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
View Model
public class MainView_VM : ViewModelBase
{
public MainView_VM()
{
ReadFile();
}
public ObservableCollection<string> FileData { get; set; }
void ReadFile()
{
//I will read file here.
}
}
Here is a very basic example of what you want to do:
Window XAML
<Window.Resources>
<local:StringToIntConverter x:Key="StringToIntConverter" />
</Window.Resources>
<StackPanel>
<TextBlock>Select Index</TextBlock>
<TextBox x:Name="theTextBox" Text="{Binding SelectedIndex,ElementName=theList,Converter={StaticResource StringToIntConverter},Mode=OneWayToSource,UpdateSourceTrigger=Explicit}" />
<Button Click="Button_Click">Select Now</Button>
<ListBox x:Name="theList">
<ListBoxItem>First</ListBoxItem>
<ListBoxItem>Second</ListBoxItem>
<ListBoxItem>Third</ListBoxItem>
</ListBox>
</StackPanel>
Window CodeBehind
private void Button_Click(object sender, RoutedEventArgs e)
{
theTextBox.GetBindingExpression(TextBox.TextProperty)?.UpdateSource();
}
Explanation
You were asking to set the index on a list from a textbox by clicking a button. We bind the TextBox to the selected index with a couple of settings:
Source: SelectedIndex
ElementName: The List/Target UI Element
Converter: Required to get from String to Int (i wrote on myself)
Mode: OneWayToSource, we force the textbox to only send values to the list and not the other way round
UpdateSourceTrigger: We do not want the binding to auto-update, we want to do this ourselves
To update the binding we use the Click Event of the button.
But what about the view model?
The operation is a View-Only operation, the ViewModel doesn't need to know anything about it, so we should leave it out of the operation. That's why I'm not using a CommandBinding.
Whoops, forgot about the UserControl
If you want to put this in a user control then i suggest that you don't create a ViewModel at all. Also in the user control you don't need DataBinding, only on the outside. Keep it simple:
UserControl XAML
<TextBlock>Select Index</TextBlock>
<TextBox x:Name="theTextBox" />
<Button Click="Button_Click">Select Now</Button>
UserControl CodeBehind
public int Index
{
get { return (int)GetValue(IndexProperty); }
set { SetValue(IndexProperty, value); }
}
public static readonly DependencyProperty IndexProperty =
DependencyProperty.Register("Index", typeof(int), typeof(ListViewIndexSelectorControl), new PropertyMetadata(0));
private void Button_Click(object sender, RoutedEventArgs e)
{
if(int.TryParse(theTextBox.Text, out int result))
{
Index = result;
}
}
MainWindow Usage XAML
<local:ListViewIndexSelectorControl Index="{Binding SelectedIndex,ElementName=theList,Mode=OneWayToSource}" />
<ListBox x:Name="theList">
<ListBoxItem>First</ListBoxItem>
<ListBoxItem>Second</ListBoxItem>
<ListBoxItem>Third</ListBoxItem>
</ListBox>
If you later on need a ViewModel, you can also use the View as the ViewModel for simple controls, just set DataContext = this; in the View's constructor or use a Name on the XAML element and bind the DataContext by ElementName.
If you are using MvvmLight, you could for example use the Messenger class to send a message from the child view model to the parent:
IndexView_VM:
internal void _View_CMD(object Parameter)
{
GalaSoft.MvvmLight.Messaging.Messenger.Default.Send(_Index);
}
MainView_VM:
public class MainView_VM : ViewModelBase
{
public MainView_VM()
{
ReadFile();
GalaSoft.MvvmLight.Messaging.Messenger.Default.Register<int>(this, index => Index = index);
}
public ObservableCollection<string> FileData { get; set; }
int _Index;
public int Index
{
get { return _Index; }
set
{
_Index = value;
RaisePropertyChanged();
}
}
void ReadFile()
{
//I will read file here.
}
}
MainView:
<ListView ItemsSource="{Binding FileData}" x:Name="listView" Grid.Column="1"
SelectedIndex="{Binding Index}">
<ListView.View>
<GridView>
<GridViewColumn Header="Data" Width="100"/>
</GridView>
</ListView.View>
</ListView>
Please refer to Laurent Bugnion's MSDN Magazine article for more information about the Messenger.
MVVM - Messenger and View Services in MVVM: https://msdn.microsoft.com/en-us/magazine/jj694937.aspx
Not sure if I understand this right. You want to set the selected item of your ListBox using the index value you type in that TextBox, is this right?
If this is is right then I have the following considerations:
In this scenario a UserControl is probably overkill. Especially if you are going to never re-use it somewhere else in your UI.
Given the first consideration, all you have to do is move that TextBox to your main view, give it a name and bind the .Text Property to your ListView's SelectedIndex Property.
Example:
<ListView SelectedIndex="{Binding ElementName=txtIndex, Path=Text, Converter={StaticResource StringToIntConverter}, UpdateSourceTrigger=PropertyChanged}" />
That converter (which you would need to implement) is needed because converting a string to an int won't probably happen automatically. UpdateSourceTrigger=PropertyChanged will update the target Property as soon as you type, removing the need for a button.
At that point you should be done.
If you absolutely need that UserControl, you could add a DependencyProperty exposing the TextBox's value. Then you could bind to that Property as in the example above.

MVVM – Hierarchies & Navigation Implicit Binding for UWP

Somewhat I've been trying to follow this MVVM tutorial using Hierarchies and navigation:
https://www.tutorialspoint.com/mvvm/mvvm_hierarchies_and_navigation.htm
I've done so far most of the tutorial, but when it comes to UWP it seems that Implicit binding is not available for UWP, so I can't replicate this tutorial, because even though I've used x:DataType with x:Key that the compiler asks for an x:key attribute in order to bind views with viewmodel, all I get is the fullname of my viewmodel instead of being able to see the actual content.
So can somebody help me how can I use hierarchies properly in UWP using Plain MVVM pattern without the help of tools such as MVVM Light or MVVM Cross.
I'll leave you the code I have so far for a UWP app:
<Page
x:Class="MVVMHeirarchiesDemo.MainPageView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MVVMHeirarchiesDemo"
xmlns:views="using:MVVMHeirarchiesDemo.Views"
xmlns:viewmodel="using:MVVMHeirarchiesDemo.ViewModel"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<!--Anytime the current view model is set to an instance of a CustomerListViewModel,
it will render out a CustomerListView with the ViewModel is hooked up. It’s an order ViewModel,
it'll render out OrderView and so on.
We now need a ViewModel that has a CurrentViewModel property and some logic and commanding
to be able to switch the current reference of ViewModel inside the property.-->
<Page.DataContext>
<viewmodel:MainPageViewModel/>
</Page.DataContext>
<Page.Resources>
<DataTemplate x:Key="CustomerTemplate" x:DataType="viewmodel:CustomerListViewModel">
<views:CustomerListView/>
</DataTemplate>
<DataTemplate x:Key="OrderTemplate" x:DataType="viewmodel:OrderViewModel">
<views:OrderView/>
</DataTemplate>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid x:Name="NavBar"
Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Content="Customers"
Command="{Binding NavCommand}"
CommandParameter="customers"
Grid.Column="0"
Grid.Row="0"/>
<Button Content="Orders"
Command="{Binding NavCommand}"
CommandParameter="orders"
Grid.Column="2"
Grid.Row="0"/>
</Grid>
<Grid x:Name="MainContent"
Grid.Row="1">
<ContentControl Content="{Binding CurrentViewModel}"/>
</Grid>
</Grid>
as you can see may main trouble are at my Page. Resources I guess with my binding at
because that line of code is not getting access to the actual content of my views.
this is my viewmodel for my main view:
namespace MVVMHeirarchiesDemo.ViewModel
{
/*Derive all of your ViewModels from BindableBase class.*/
public class MainPageViewModel : BindableBase
{
public MainPageViewModel()
{
NavCommand = new MyCommand<string>(OnNavigation);
}
private CustomerListViewModel _customerListViewModel = new CustomerListViewModel();
private OrderViewModel _orderViewModel = new OrderViewModel();
private BindableBase _currentViewModel;
public BindableBase CurrentViewModel
{
get
{
return _currentViewModel;
}
set
{
SetProperty(ref _currentViewModel, value);
}
}
public MyCommand<string> NavCommand { get; private set; }
private void OnNavigation(string destination)
{
switch (destination)
{
case "orders":
{
CurrentViewModel = _orderViewModel;
break;
}
case "customers":
default:
CurrentViewModel = _customerListViewModel;
break;
}
}
}
}
and finally this is my helper bindable class:
namespace MVVMHeirarchiesDemo
{
/*The main idea behind this class is to encapsulate the INotifyPropertyChanged implementation
* and provide helper methods to the derived class so that they can easily trigger the appropriate notifications.
* Following is the implementation of BindableBase class.*/
public class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual void SetProperty<T>(ref T member, T val, [CallerMemberName]string propertyName = null)
{
if (object.Equals(member, val))
return;
member = val;
OnPropertyChanged(propertyName);
}
}
}
I hope someone can help me out with this one.
well It took me a while but i was able to understand how to use DataTemplateSelector class, it turns out that this work around fit nicely to my problem since there is no implicit binding for UWP.
So if you are exploring UWP there isnt IMPLICIT BINDING you have to use explicit binding in order to make this specific problem work.
So this was my solution, I still use my BindableBase because it help me to choose the proper ViewModel for the View i'm calling, so there is no need to change it.
firstable I've created a Template class so I can retrieve the properties that will help me work with ExplicitBinding:
public class Template
{
public string DataType { get; set; }
public DataTemplate DataTemplate { get; set; }
}
Then I'll use a Collection but I'll use a Facade Pattern on this one, I kind love patterns are fun and elegant.
public class TemplateCollection : Collection<Template>
{
}
Then I've used a class by another answer that helps me to reuse it to solve my problem:
public class MyDataTemplateSelector : DataTemplateSelector
{
public TemplateCollection Templates { get; set; }
private ICollection<Template> _templateCache { get; set; }
public MyDataTemplateSelector()
{
}
private void InitTemplateCollection()
{
_templateCache = Templates.ToList();
}
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
if (_templateCache == null)
{
InitTemplateCollection();
}
if (item != null)
{
var dataType = item.GetType().ToString();
var match = _templateCache.Where(m => m.DataType == dataType).FirstOrDefault();
if (match != null)
{
return match.DataTemplate;
}
}
return base.SelectTemplateCore(item, container);
}
}
this class can be found here: How to associate view with viewmodel or multiple DataTemplates for ViewModel?
just I dont like to steal credits, but I did learned from this answer and my partner sugesstion MLavoie.
so this is my Fix view thanks to this I'm able to use navigation and also created a Hierarchical MVVM Pattern.
<Page
x:Class="MVVMHeirarchiesDemo.MainPageView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MVVMHeirarchiesDemo"
xmlns:dtempsltor="using:MVVMHeirarchiesDemo.Templates"
xmlns:views="using:MVVMHeirarchiesDemo.Views"
xmlns:viewmodel="using:MVVMHeirarchiesDemo.ViewModel"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<!--Anytime the current view model is set to an instance of a CustomerListViewModel,
it will render out a CustomerListView with the ViewModel is hooked up. It’s an order ViewModel,
it'll render out OrderView and so on.
We now need a ViewModel that has a CurrentViewModel property and some logic and commanding
to be able to switch the current reference of ViewModel inside the property.-->
<Page.DataContext>
<viewmodel:MainPageViewModel/>
</Page.DataContext>
<Page.Resources>
<dtempsltor:TemplateCollection2 x:Key="templates">
<dtempsltor:Template DataType="MVVMHeirarchiesDemo.ViewModel.CustomerListViewModel">
<dtempsltor:Template.DataTemplate>
<DataTemplate x:DataType="viewmodel:CustomerListViewModel">
<views:CustomerListView/>
</DataTemplate>
</dtempsltor:Template.DataTemplate>
</dtempsltor:Template>
<dtempsltor:Template DataType="MVVMHeirarchiesDemo.ViewModel.OrderViewModel">
<dtempsltor:Template.DataTemplate>
<DataTemplate x:DataType="viewmodel:OrderViewModel">
<views:OrderView/>
</DataTemplate>
</dtempsltor:Template.DataTemplate>
</dtempsltor:Template>
</dtempsltor:TemplateCollection2>
<dtempsltor:MyDataTemplateSelector x:Key="MyDataTemplateSelector"
Templates="{StaticResource templates}"/>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid x:Name="NavBar"
Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Content="Customers"
Command="{Binding NavCommand}"
CommandParameter="customers"
Grid.Column="0"
Grid.Row="0"/>
<Button Content="Orders"
Command="{Binding NavCommand}"
CommandParameter="orders"
Grid.Column="2"
Grid.Row="0"/>
</Grid>
<Grid x:Name="MainContent"
Grid.Row="1">
<ContentControl ContentTemplateSelector="{StaticResource MyDataTemplateSelector}"
Content="{Binding CurrentViewModel}"/>
</Grid>
</Grid>
thanks for those who helped me enlight myself it was great, to be able to solve it with some hints and also felt good to be able to solve it, I kinda love to code in C# and Xaml.

How to implement PropertyChanged in order to refresh my Datagrid after my ComboxSelection has changed

Currently I have a datagrid and a combobox. I can't seem to get my datagrid to refresh on selectionchanged of my combobox. I'm getting the value (_mySelectedValue) but my datagrid never loads. I tried aDataGrid.refresh.
The grid should load when I select the Combobox.Name, which gives me the ID in _mySelectedID, which my query then uses to query the database and refill my collection. (I think..)
ViewModel
public class UserViewModel : ViewModelBase, IUserViewModel
{
public DataEntities _context = new DataEntities();
public ObservableCollection<UserChoice> userChoices { get; set; }
public ObservableCollection<CompanyName> companyNames { get; set; }
public ObservableCollection<UserTable> userTables { get; set; }
public UserViewModel()
{
GetID();
GetDataAsync();
}
public async Task GetDataAsync()
{
var serv = (from s in _context.UserChoices
join sa in _context.CompanyNames on s.CompanyID equals sa.CompanyID
where sa.CompanyID == mySelectedItem //crap left this out
select s).ToList();
userChoices = new ObservableCollection<UserChoice>(serv);
}
public async Task GetID()
{
var data = _context.CompanyNames.OrderBy(o => o.CompanyID).ToList();
CompanyNames = new ObservableCollection<CompanyName>(data);
}
public byte _mySelectedItem;
public Byte MySelectedItem
{
get { return _mySelectedItem; }
set
{
_mySelectedItem = value;
OnPropertyChanged("MySelectedItem");
}
}
}
XAML
<Grid Margin="0,0,-200,0">
<DataGrid x:Name="aDataGrid"
ItemsSource="{Binding userChoices, UpdateSourceTrigger=PropertyChanged}"
RowDetailsVisibilityMode="VisibleWhenSelected"
EnableRowVirtualization="True" AutoGenerateColumns="False"
HorizontalAlignment="Left" Height="159"
VerticalAlignment="Top" Width="337"
Margin="156,57,0,0">
<DataGrid.Columns>
<DataGridTextColumn x:Name="actChoice" Width="*" Header="Choice"
Binding="{Binding Choice, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<DataGridTextColumn x:Name="actDescription" Width="*" Header="Description"
Binding="{Binding Description, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataGrid.Columns>
</DataGrid>
<Grid x:Name="grid1" HorizontalAlignment="Left" VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Content="Company Name:" Grid.Column="0" HorizontalAlignment="Left" Margin="3" Grid.Row="0" VerticalAlignment="Center"/>
<ComboBox x:Name="companyNameComboBox" Grid.Column="1"
DisplayMemberPath="CompanyName"
HorizontalAlignment="Left" Height="Auto"
ItemsSource="{Binding companyNames}"
Margin="3" Grid.Row="0"
VerticalAlignment="Center" Width="120"
SelectedValuePath="CompanyID"
SelectedValue="{Binding Path= MySelectedItem, Mode= TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedIndex="2">
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel/>
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
</ComboBox>
</Grid>
</Grid>
You need to call GetDataAsync() inside your setter for MySelectedItem, and then make userChoices raise a property changed event.
Also, you aren't awaiting any calls in your async methods, so you shouldn't make them async.
public void GetData()
{
// Also remember to plug in the correct company ID!
// I removed the join, too, because it looks like you don't need it.
// If you actual query is more complicated then feel free to add it back.
var serv = (from s in _context.UserChoices
where s.CompanyID == MySelectedItem
select s).ToList();
userChoices = new ObservableCollection<UserChoice>(serv);
}
public void GetID()
{
var data = _context.CompanyNames.OrderBy(o => o.CompanyID).ToList();
CompanyNames = new ObservableCollection<CompanyName>(data);
}
private ObservableCollection<UserChoice> _userChoices;
public ObservableCollection<UserChoice> userChoices
{
get { return _userChoices; }
set
{
_userChoices= value;
OnPropertyChanged("userChoices ");
}
}
private byte _mySelectedItem;
public Byte MySelectedItem
{
get { return _mySelectedItem; }
set
{
_mySelectedItem = value;
GetData();
OnPropertyChanged("MySelectedItem");
}
}
Edit
To make a save method (based on your comment) I would use an ICommand since you have a view model. If you do this, you will first need to install the Prism.Mvvm NuGet package to get the DelegateCommand class (in the Microsoft.Practices.Prism.Commands namespace).
Then add this code to your view model:
public void Save()
{
var context = new AADataEntities();
// Make changes to the context here...
context.SaveChanges();
}
private ICommand _saveCommand = new DelegateCommand(Save);
public ICommand SaveCommand
{
get { return _saveCommand; }
}
Now wire up the save command in the xaml like this:
<Button Content="Save" Command="{Binding SaveCommand}" />
Independent of code incoherence pointed by #Jevans92, I can see one problem, which is the SelectedValuePath + SelectedValue combination on Combobox.
You see, it only looks up for the selected value and updates it visual, but it never updates de binded SelectedValue back. So, if you have a pre-set SelectedValue and load the UserControl, then the Combobox looks up for the correct value to show, but if you change selection, it does not update the SelectedValue object bound to the control.
Long story short: Try removing both SelectedValuePath and SelectedValue and using SelectedItem instead.
If you have to deal only with selecting from the UI to the VM, then you don't event need to call PropertyChanged, as it is only used to notify the UI about changes on the VM.
But, if you need to also set the SelectedItem on the VM for the UI to show, then you will have to implement it.
Also note that, if you are dealing with different instances on your ItemsSource and your SelectedItem, you'd better override Equals + GetHashCode on that class, else it will never be looked up on your SelectedItem.

design pattern problem

Hello I have a application design problem and I home you can help me solve it....
This is my first application in silverlight and the first application using mvvm design pattern and I am not sure I am applying mvvm how I am supposed to..
The application is a dynamic application and at runtime I can add/remove usercontrols...
So I have a MainWindowView that has behind a MainWindowModel.
The MainWindowModel has a list of Workspaces witch are in fact WorkspaceModel classes...
I have multiple UserControls and everyone off them has his own view model witch inherits WorkspaceModel.
The Workspaces property is binded to a container in MainWindowView so adding to the Workspaces list a new UserControlModel will automatically add that control to the view.
Now where is my problem... I want to make this dynamically added usercontrols to interact. Lets say one user control is a tree and one is a grid... I want a method to say that Itemsource property of Grid UserControl Model (WorkspaceModel) to be binded to SelectedNode.Nodes Property from the Tree Usercontrol Model (WorkspaceModel).
The MainWindowModel has a property name BindingEntries witch has a list of BindingEntry...
BindingEntry stores the source property and the destination property of the binding like my workspacemodel_1.SelectedNode.Nodes -> workspacemodel_2.ItemSource...
Or as a variation the MainWindowView has a property ViewStateModel. This ViewStateModel class has dynamic created properties - "injected" with property type descriptors/reflections etc... So the user can define at run time the displayed usercontrols (by modifying the Workspaces list) and can define a view model (the ViewStameModel) and the binding is between workspacemodel properties and this ViewStateModel properties...
So I actually want to bind 2 view models one to another... How to do that?
Create an observer pattern?
Is the design until now totally wrong?
I hope it makes sense.....
I will try to add some sample code...the project is quite big I will try co put only the part I have mentioned in the problem desciption... I hope I will not miss any pice of code
First of all
public class MainWindowModel : ModelBase
{
private ObservableCollection<WorkspaceModel> _workspaces;
private ModelBase _userViewModel;
public MainWindowModel()
{
base.DisplayName = "MainWindowModel";
ShowTreeView(1);
ShowTreeView(2);
ShowGridView(3);
ShowGridView(4);
UserViewModel = new ViewModel(); //this is the ViewStateModel
}
void ShowTreeView(int id)
{
WorkspaceModel workspace = ControlFactory.CreateModel("TreeControlModel", id);
this.Workspaces.Add(workspace);
OnPropertyChanged("Workspaces");
SelectedWorkspace = workspace;
}
void ShowGridView(int id)
{
WorkspaceModel workspace = ControlFactory.CreateModel("GridControlModel", id);
this.Workspaces.Add(workspace);
OnPropertyChanged("Workspaces");
SelectedWorkspace = workspace;
}
public ObservableCollection<WorkspaceModel> Workspaces
{
get
{
if (_workspaces == null)
{
_workspaces = new ObservableCollection<WorkspaceModel>();
}
return _workspaces;
}
}
public ModelBase UserViewModel
{
get
{
return _userViewModel;
}
set
{
if (_userViewModel == value)
{
return;
}
_userViewModel = value;
OnPropertyChanged("UserViewModel");
}
}
}
snippets from MainappView
<DataTemplate x:Key="WorkspaceItemTemplate">
<Grid >
//workaround to use Type as in WPF
<Detail:DetailsViewSelector Content="{Binding}" TemplateType="{Binding}" >
<Detail:DetailsViewSelector.Resources>
<DataTemplate x:Key="TreeControlModel" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<TreeControl:TreeControlView />
</DataTemplate>
<DataTemplate x:Key="GridControlModel" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<GridControl:GridControlView />
</DataTemplate>
<DataTemplate x:Key="EmptyTemplate">
</DataTemplate>
</Detail:DetailsViewSelector.Resources>
</Detail:DetailsViewSelector>
</Grid>
</DataTemplate>
<DataTemplate x:Key="WorkspacesTemplate">
<ItemsControl IsTabStop="False" ItemsSource="{Binding}" ItemTemplate="{StaticResource WorkspaceItemTemplate}" Margin="6,2"/>
</DataTemplate>
</UserControl.Resources>
<toolkit:HeaderedContentControl Grid.Column="2" HorizontalAlignment="Stretch" Name="hccWorkspaces" VerticalAlignment="Top" Header="Workspaces" Content="{Binding Source={StaticResource vm}, Path=Workspaces}" ContentTemplate="{StaticResource WorkspacesTemplate}"/>
public class ControlFactory
{
public static WorkspaceModel CreateModel(string type, int id)
{
switch (type)
{
case "TreeControlModel": return new TreeControlModel() { Id=id}; break;
case "GridControlModel": return new GridControlModel() { Id = id }; break;
}
return null;
}
}
public class GridControlModel : WorkspaceModel
{
#region Fields
ObservableCollection<TreeItem> _items;
TreeItem _selectedItem;
#endregion // Fields
#region Constructor
public GridControlModel()
{
base.DisplayName = "GridControlModel";
}
#endregion // Constructor
#region Public Interface
public ObservableCollection<TreeItem> Items
{
get
{
return _items;
}
set
{
if (_items == value)
return;
_items = value;
OnPropertyChanged("Items");
}
}
public TreeItem SelectedItem
{
get
{
return _selectedItem;
}
set
{
if (_selectedItem.Equals(value))
{
return;
}
_selectedItem = value;
OnPropertyChanged("SelectedItem");
}
}
#endregion // Public Interface
#region Base Class Overrides
protected override void OnDispose()
{
this.OnDispose();
}
#endregion // Base Class Overrides
}
<Grid x:Name="LayoutRoot" Background="White">
<sdk:DataGrid Grid.Column="2" Grid.Row="1" HorizontalAlignment="Stretch" Name="dataGrid1" VerticalAlignment="Stretch" ItemsSource="{Binding Path=SelectedTreeNode.Children}" IsEnabled="{Binding}" AutoGenerateColumns="False">
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="Id" Width="Auto" Binding="{Binding Id}" />
<sdk:DataGridTextColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="Name" Width="Auto" Binding="{Binding Name}"/>
</sdk:DataGrid.Columns>
</sdk:DataGrid>
</Grid>
</UserControl>
For communicating between your view models I would suggest taking a look at the Messenger implementation in MVVM Light as a simple solution.
Alternatively, the Mediator Pattern as described here might be interesting: http://marlongrech.wordpress.com/2008/03/20/more-than-just-mvc-for-wpf/

Categories

Resources