linking MVVM class to XAML - c#

I have the ViewModel Class below that i am using as a DataContext in XAML..
public class ViewModel
{
public ObservableCollection<Model> Collection { get; set; }
public ViewModel()
{
Collection = new ObservableCollection<Model>();
GenerateDatas();
}
private void GenerateDatas()
{
this.Collection.Add(new Model(0, 1));
this.Collection.Add(new Model(1, 2));
this.Collection.Add(new Model(2, 3));
this.Collection.Add(new Model(3, 4));
}
}
public class Model
{
public double X { get; set; }
public double Y { get; set; }
public Model(double x, double y)
{
X = x;
Y = y;
}
}
i link it by creating a namespace of the application in the XAML as below:
xmlns:local="clr-namespace:MyApplication"
i then access the ViewModel as follows to serve as DataContext:
<sparrow:SparrowChart.DataContext>
<local:ViewModel/>
</sparrow:SparrowChart.DataContext>
But i get an error that the name ViewModel doesn't exist in the local namespace..how do i go about fixing this?
The full XAML file:
<phone:PhoneApplicationPage
x:Class="SparrowCharts.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clrnamespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:sparrow="clr-namespace:Sparrow.Chart;assembly=Sparrow.Chart.WP8.45"
xmlns:local="clr-namespace:MyApplication"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
<TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<sparrow:SparrowChart>
<sparrow:SparrowChart.DataContext>
<local:ViewModel/>
</sparrow:SparrowChart.DataContext>
<sparrow:SparrowChart.XAxis>
<sparrow:LinearXAxis/>
</sparrow:SparrowChart.XAxis>
<sparrow:SparrowChart.YAxis>
<sparrow:LinearYAxis/>
</sparrow:SparrowChart.YAxis>
<sparrow:LineSeries PointsSource="{Binding Collection}" XPath="X" YPath="Y"/>
</sparrow:SparrowChart>
</Grid>
</Grid>
the C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using MyApplication.Resources;
using System.Collections.ObjectModel;
namespace MyApplication
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
// Create a ViewModel
public class ViewModel
{
public ObservableCollection<Model> Collection { get; set; }
public ViewModel()
{
Collection = new ObservableCollection<Model>();
GenerateDatas();
}
private void GenerateDatas()
{
this.Collection.Add(new Model(0, 1));
this.Collection.Add(new Model(1, 2));
this.Collection.Add(new Model(2, 3));
this.Collection.Add(new Model(3, 4));
}
}
public class Model
{
public double X { get; set; }
public double Y { get; set; }
public Model(double x, double y)
{
X = x;
Y = y;
}
}
}
}

check on your curly braces,the ViewModel class should only be enclosed by the namespace curly brace and not the MainPage curly brace.Then you could create a new file for the Model class or place it way below the MainPage on its own.

Try this code :
<phone:PhoneApplicationPage
x:Class="SparrowCharts.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clrnamespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:sparrow="clr-namespace:Sparrow.Chart;assembly=Sparrow.Chart.WP8.45"
xmlns:local="clr-namespace:MyApplication"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<phone:PhoneApplicationPage.DataContext>
<local:ViewModel />
</phone:PhoneApplicationPage.DataContext>
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
<TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<sparrow:SparrowChart>
<sparrow:SparrowChart.XAxis>
<sparrow:LinearXAxis/>
</sparrow:SparrowChart.XAxis>
<sparrow:SparrowChart.YAxis>
<sparrow:LinearYAxis/>
</sparrow:SparrowChart.YAxis>
<sparrow:LineSeries PointsSource="{Binding DataContext.Collection, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type phone:PhoneApplicationPage}}}" XPath="X" YPath="Y"/>
</sparrow:SparrowChart>
</Grid>
</Grid>

If you are sure that the view model resides in the correct namespace, try this declaration:
xmlns:local="clr-namespace:MyApplication;assembly="

The ViewModel is nested within the Window. So its full name is MyApplication.MainWindow.ViewModel
Pull it out and put it in its own file and the correct namespace.
By the way: make sure the ViewModel class implements INotifyPropertyChanged

Related

Use UserControl in ListView UWP, Databinding Issue

I wanted to create an App to manage various Project, so i created a class to represent those Projects. In order to display them i created a user Control which should display then and later also manage the interaction between User and Project-Object.
I tried to display a list of Projects in a Page but it does not work.
I am not sure what to bind to in the Data Template, none of the ways i tried worked.
I also used the live visual tree, and i think the Property Project of ProjectViewer is correctly set, but still the Textbook does not display the Name of the Project. (But I'm not so familiar with the live visual tree so i could be wrong).
If i use the User Control as a single instance and not in a list i can set the Project property and the Name gets displayed.
I think it is an issue with the DataBinding, but i couldn't work it out.
Any help would be appreciated since this is only the very first step of the App and I'm already stuck.
Here is a minimal example i created to reproduce the problem:
I have a class Project:
using System.Collections.Generic;
using Windows.UI.Xaml;
namespace ProjectTimeTracker
{
public class Project:DependencyObject
{
public string ProjName
{
get { return (string)GetValue(ProjNameProperty); }
set { SetValue(ProjNameProperty, value); }
}
public static readonly DependencyProperty ProjNameProperty =
DependencyProperty.Register(nameof(ProjName), typeof(string), typeof(Project), new PropertyMetadata("TestName"));
public Project(){}
}
}
And i created the UserControl ProjectViewer:
namespace ProjectTimeTracker.UI
{
public sealed partial class ProjectViewer : UserControl
{
public Project Project
{
get { return (Project)GetValue(ProjectProperty); }
set { SetValue(ProjectProperty, value); }
}
public static readonly DependencyProperty ProjectProperty =
DependencyProperty.Register(nameof(Project), typeof(Project), typeof(ProjectViewer), new PropertyMetadata(null));
public ProjectViewer()
{
this.InitializeComponent();
}
}
}
which has the following xaml code:
<UserControl
x:Class="ProjectTimeTracker.UI.ProjectViewer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ProjectTimeTracker.UI"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="100"
d:DesignWidth="400">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="38"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<RadioButton x:Name="RBSelector" HorizontalAlignment="Left" Margin="8,0,0,0" VerticalAlignment="Center" Grid.RowSpan="2"/>
<TextBlock x:Name="TBName" Grid.Row="0" Grid.Column="1" Text="{x:Bind Project.ProjName}" VerticalAlignment="Center" HorizontalAlignment="Left" Style="{ThemeResource TitleTextBlockStyle}" Width="110"/>
<TextBlock x:Name="TBTotalTime" Grid.Row="1" Grid.Column="1" Text="NYI" HorizontalAlignment="Left" VerticalAlignment="Center" Style="{ThemeResource CaptionTextBlockStyle}" Margin="0,-4,0,0"/>
</Grid>
</UserControl>
I try to use that User Control in the mainpage to create a list of Projects
using System.Collections.Generic;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace ProjectTimeTracker
{
public sealed partial class MainPage : Page
{
public List<Project> Projects
{
get { return (List<Project>)GetValue(ProjectsProperty); }
set { SetValue(ProjectsProperty, value); }
}
public static readonly DependencyProperty ProjectsProperty =
DependencyProperty.Register(nameof(Projects), typeof(List<Project>), typeof(MainPage), new PropertyMetadata(new List<Project>()));
public MainPage()
{
this.InitializeComponent();
Projects.Add(new Project() { ProjName="Projekt1"});
list.ItemsSource = Projects;
}
}
}
The xaml looks like this:
<Page xmlns:UI="using:ProjectTimeTracker.UI"
x:Class="ProjectTimeTracker.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ProjectTimeTracker"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<ListView x:Name="list" HorizontalAlignment="Center" VerticalAlignment="Center">
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:Project">
<UI:ProjectViewer Project="{x:Bind }"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Page>
Use UserControl in ListViev UWP, Databinding Issue
I have modified your code, please refer the following,
ProjectViewer.xaml.cs
public sealed partial class ProjectViewer : UserControl
{
public ProjectViewer()
{
this.InitializeComponent();
}
public Project ProjectSource
{
get { return (Project)GetValue(ProjectSourceProperty); }
set { SetValue(ProjectSourceProperty, value); }
}
public static readonly DependencyProperty ProjectSourceProperty =
DependencyProperty.Register("ProjectSource", typeof(Project), typeof(ProjectViewer), new PropertyMetadata(0, new PropertyChangedCallback(CallBack)));
private static void CallBack(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var current = d as ProjectViewer;
if (e.NewValue != e.OldValue)
{
current.TBName.Text = (e.NewValue as Project).ProjName;
}
}
}
public class Project
{
public string ProjName { get; set; }
public Project()
{
}
}
ProjectViewer.xaml
<RadioButton
x:Name="RBSelector"
Grid.RowSpan="2"
Margin="8,0,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
/>
<TextBlock
x:Name="TBName"
Grid.Row="0"
Grid.Column="1"
Width="110"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Style="{ThemeResource TitleTextBlockStyle}"
/>
<TextBlock
x:Name="TBTotalTime"
Grid.Row="1"
Grid.Column="1"
Margin="0,-4,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Style="{ThemeResource CaptionTextBlockStyle}"
Text="NYI"
/>
Usage
public sealed partial class MainPage : Page
{
public List<Project> Projects = new List<Project>();
public MainPage()
{
this.InitializeComponent();
Projects.Add(new Project() { ProjName = "Projekt1" });
list.ItemsSource = Projects;
}
public string TestString { get; set; }
}
Xaml
<ListView
x:Name="list"
HorizontalAlignment="Center"
VerticalAlignment="Center"
>
<ListView.ItemTemplate>
<DataTemplate >
<local:ProjectViewer ProjectSource="{Binding }" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

How to make a Save/Reset options page that has two sub-pages using WPF and C#

I would like to make a page that contains two sub-pages of options.
The problem I've encountered is that I can't access the objects from sub-pages of the main page. I should note that I use only DataContext to script behind.
And here is some of the code that will help you understand better what I mean:
StartPage.xaml
<Page x:Class="WpfApp.StartPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Title="startPage">
<Grid Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<StackPanel>
<Button Content="Page 1" Command="{Binding FirstPageCommand}"/>
<Button Content="Page 2" Command="{Binding SecondPageCommand}"/>
</StackPanel>
<Frame x:Name="frame" Grid.Column="1" NavigationUIVisibility="Hidden"
Source="Page1.xaml"/>
<StackPanel Grid.Column="1" Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button Content="Reset" Margin="10" Command="{Binding ResetCommand}"/>
<Button Content="Save" Margin="10" Command="{Binding SaveCommand}"/>
</StackPanel>
</Grid>
StartPage.xaml.cs
using System.Windows.Controls;
namespace WpfApp
{
/// <summary>
/// Interaction logic for StartPage.xaml
/// </summary>
public partial class StartPage : Page
{
public StartPage()
{
InitializeComponent();
DataContext = new StartPage_DataContext(this);
}
}
}
StartPage_DataContext.cs
using System.Windows.Controls;
using System.Windows.Input;
namespace WpfApp
{
public class StartPage_DataContext
{
private Page _Page;
public StartPage_DataContext(Page page)
{
_Page = page;
FirstPageCommand = new RelayCommand(() => FirstPage());
SecondPageCommand = new RelayCommand(() => SecondPage());
SaveCommand = new RelayCommand(() => Save());
ResetCommand = new RelayCommand(() => Reset());
}
private void FirstPage()
{
(_Page as StartPage).frame.NavigationService.Navigate(new Page1());
}
private void SecondPage()
{
(_Page as StartPage).frame.NavigationService.Navigate(new Page2());
}
private void Save()
{
//Here is where I need code for saving both "Page1" and "Page2" elements to Settings class.
//Exeple : Settings._firstCB = Page1.firstCB.IsCheked.Value;
// Settings._secondCB = Page2.firstCB.IsCheked.Value;
}
private void Reset()
{
//Here is where I need code for setting both "Page1" and "Page2" elements to some default values.
//Exemple : Page1.firstCB.IsCheked.Value = false;
// Page2.firstCB.IsCheked.Value = true;
}
public ICommand FirstPageCommand { get; private set; }
public ICommand SecondPageCommand { get; private set; }
public ICommand SaveCommand { get; private set; }
public ICommand ResetCommand { get; private set; }
}
}
Page1.xaml (page2 is similar the only difference is the naming of elements convention)
<Page x:Class="WpfApp.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Title="Page1">
<Grid Background="White">
<StackPanel>
<CheckBox x:Name="firstCB" Content="First Combo Box"/>
<CheckBox x:Name="secondCB" Content="Second Combo Box"/>
<ComboBox x:Name="firstCombo">
<ComboBoxItem Content="First Item"/>
<ComboBoxItem Content="Second Item"/>
</ComboBox>
</StackPanel>
</Grid>
Not sure if you have view models for your sub pages,
If you do have, one way of accessing properties of those viewmodel for your check box would be as shown below.
var tt = (((_Page as StartPage).frame.NavigationService.Content as Page1).DataContext as Page1ViewModel).IsCBChecked;

Listbox cannot display in WP8 Emulator

It's wired. I'm developing a WP8 app. the XAML code is:
<phone:PhoneApplicationPage
x:Class="WPTestService4DotNet.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
<TextBlock x:Name="PageTitle" Margin="9,-7,0,0" Style="{StaticResource PhoneTextNormalStyle}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="avatar" FontSize="18"></TextBlock>
<ListBox Grid.Row="1" x:Name="ResultBox" BorderBrush="Bisque" BorderThickness="4" DataContext="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="inner display" FontSize="18"></TextBlock>
<TextBlock Text="{Binding Path=Id}" FontSize="18" FontStyle="Italic" TextWrapping="Wrap"></TextBlock>
<TextBlock Text="{Binding Path=Title}" FontSize="18" TextWrapping="Wrap"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
and the CS code is:
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
var results = new List<Result>();
results.Add(new Result() { Id = "1", Title = "first" });
results.Add(new Result() { Id = "2", Title = "second" });
results.Add(new Result() { Id = "3", Title = "third" });
this.DataContext = results;
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
public class Result
{
public string Id { set; get; }
public string Title { set; get; }
}
}
Content in the listbox doesn't display in windows phone 8 emulator.
I guess no error in my code it's so simple , but I dont' know why
It's the ItemsSource that determines the output from the <ListBox.ItemTemplate>
this.ResultBox.ItemsSource = results;
Generally you set the DataContext to the ViewModel, then the ItemsSource to a collection/list that is inside the ViewModel.
You could alternatively set ItemsSource="{Binding}" int your ListBox.

Binding ContentControl to a View for a ViewModel

I'm using MVVM in a windows phone 8 application. I would like to move from 1 view model to another inside my shell view model. I can't seem to get the ContentControl to bind to a template that is a usercontrol/phoneApplicationPage over the view model.
What am I missing?
I'm trying to avoid things like MVVM light. (I want my app to be as small a download as possible) And this should be possible to do.
P.S. I'm still pretty new to WPF/WP8
Here is a sample of what I have so far, Excuse the dumb functionality :)
/** The Shell view **/
<phone:PhoneApplicationPage
x:Class="PhoneAppWithDataContext.Navigation.ViewModelNavigation"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d"
shell:SystemTray.IsVisible="True"
xmlns:vm="clr-namespace:PhoneAppWithDataContext.Navigation">
<phone:PhoneApplicationPage.DataContext>
<vm:AppViewModel/>
</phone:PhoneApplicationPage.DataContext>
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Key="MonthViewModel">
<vm:MonthViewControl/>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ContentControl Content="{Binding CurrentViewModel}"
ContentTemplate="{Binding ContentTemplate}"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Stretch"/>
</Grid>
<Button Content="Change VM" Command="{Binding ChangeViewModelCommand}"/>
</Grid>
</phone:PhoneApplicationPage>
/** Shell/Application View Model **/
public class AppViewModel : ViewModelBase
{
private ViewModelBase _currentViewModel;
private List<ViewModelBase> _viewModels = new List<ViewModelBase>();
private byte _month = 1;
public ViewModelBase CurrentViewModel
{
get
{
return _currentViewModel;
}
set
{
if (_currentViewModel == value)
return;
_currentViewModel = value;
NotifyPropertyChanged("CurrentViewModel");
}
}
public DataTemplate SelectedTemplate
{
get
{
if (_currentViewModel == null)
return null;
return DataTemplateSelector.GetTemplate(_currentViewModel);
}
}
public List<ViewModelBase> ViewModels
{
get
{
return _viewModels;
}
}
public AppViewModel()
{
ViewModels.Add(new MonthViewModel(_month));
CurrentViewModel = ViewModels.FirstOrDefault();
}
private ICommand _changeViewModelCommand;
public ICommand ChangeViewModelCommand
{
get
{
return _changeViewModelCommand ?? (_changeViewModelCommand = new GenericCommand(() =>
{
_month++;
var newVM = new MonthViewModel(_month);
ViewModels.Add(newVM);
CurrentViewModel = newVM;
}, true));
}
}
private void ChangeViewModel(ViewModelBase viewModel)
{
if (!ViewModels.Contains(viewModel))
ViewModels.Add(viewModel);
CurrentViewModel = ViewModels.FirstOrDefault(vm => vm == viewModel);
}
}
/** DataTemplateSelector **/
public static class DataTemplateSelector
{
public static DataTemplate GetTemplate(ViewModelBase param)
{
Type t = param.GetType();
return App.Current.Resources[t.Name] as DataTemplate;
}
}
/** User Control **/
<UserControl x:Class="PhoneAppWithDataContext.Navigation.MonthViewControl"
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"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
d:DesignHeight="480" d:DesignWidth="480"
xmlns:vm="clr-namespace:PhoneAppWithDataContext.Navigation">
<UserControl.DataContext>
<vm:MonthViewModel/>
</UserControl.DataContext>
<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Text="Id" Width="100" VerticalAlignment="Center" Grid.Row="0" Grid.Column="0" />
<TextBlock Text="{Binding Id}" Width="100" VerticalAlignment="Center" Grid.Row="0" Grid.Column="1" />
<TextBlock Text="Name" Width="100" VerticalAlignment="Center" Grid.Row="1" Grid.Column="0" />
<TextBlock Text="{Binding Name}" Width="100" VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" />
</Grid>
</UserControl>
/** ViewModelBase **/
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
/** View model that the user control should bind to **/
public sealed class MonthViewModel : ViewModelBase
{
private byte _id;
private string _name;
public MonthViewModel()
{
}
public MonthViewModel(byte id)
{
_id = id;
_name = "Month " + id.ToString() + " of the year";
}
public override string ToString()
{
return _name;
}
public byte Id
{
get
{
return _id;
}
}
public string Name
{
get
{
return _name;
}
}
}
I believe the problem here is:
<UserControl.DataContext>
<vm:MonthViewModel/>
</UserControl.DataContext>
When your Content is changed from one MonthViewModel to the next, the DataContext of the returned DataTemplate is set to the object bound to Content. Well, once that DataContext is set, you should be good to go, but once the UserControl is loaded, it is resetting the DataContext to a new instace of an empty MonthViewModel (vm:MonthViewModel). Get rid of that explicit DataContext declaration--in other words delete the code that I posted above.
That way, when you first call CurrentViewModel and INPC is raised, it won't reset the DataContext. When you switch between CurrentViewModel's that are of MonthViewModel type, your UserControl won't call InitializeComponent again, instead the DataContext will change.
EDIT
In addition, if you still aren't seeing changes, then I would point to SelectedTemplate property. Instead of the null check in the property, just pass null to the GetTemplate. Inside of GetTemplate, check for null and return null there if it is null.

WPF bind DataContext in xaml to ViewModel in code

I have this simplified version of my app in XAML:
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:uc="clr-namespace:myApp.MyControls"
x:Class="myApp.View.MyItem"
x:Name="testWind"
Width="Auto" Height="Auto" Background="White">
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<GroupBox x:Name="GroupBox" Header="G" Grid.Row="0">
<WrapPanel>
<GroupBox x:Name="GroupBox11">
<StackPanel Orientation="Vertical">
<uc:customControl1 Margin="0,4,0,0"
property1="{Binding prop1.property1}"
property2="{Binding prop1.property2}"
property3="{Binding prop1.property3}"/>
<uc:customControl2 Margin="0,4,0,0"
property1="{Binding prop2.property1}"
property2="{Binding prop2.property2}"
property3="{Binding prop2.property3}"/>
</StackPanel>
</GroupBox>
</WrapPanel>
</GroupBox>
</Grid>
</UserControl>
In C# I have this:
namespace MyApp.ViewModel
{
public class MyItemViewModel
{
public object prop1 { get; set; }
public object prop2 { get; set; }
}
}
In MyItem.cs I do this:
namespace MyApp.View
{
public partial class MyItem : UserControl
{
public MyItem()
{
this.InitializeComponent();
MyItemViewModel vm = new MyItemViewModel();
vm.prop1 = new blah blah(); // setting properties
vm.prop2 = new blah blah(); // setting properties
this.DataContext = vm;
}
}
}
When you end up having too many controls, this can become difficult to maintain. So, how can I tell XAML to do something like:
<uc:customControl1 Margin="0,4,0,0" DataContext="prop1"/>
<uc:customControl2 Margin="0,4,0,0" DataContext="prop2"/>
you could just give each control a unique name
<uc:customControl1 x:Name="mycontrol1" Margin="0,4,0,0" DataContext="prop1"/>
<uc:customControl2 x:Name="mycontrol2" Margin="0,4,0,0" DataContext="prop2"/>
then in your code , you could just change the data context
mycontrol1.DataContext = vm1;
mycontrol2.DataContext = vm2;

Categories

Resources