L'esempio e' composto da una finestra principale MainWindow1.xaml in cui a runtime viene caricata una pagina XAML, quindi associata ad un contesto dati.
La particolarita' di questa applicazione e' che i binding previsti nello XAML vengono impostati correttamente, compresi i comandi.
In questo modo e' possibile creare visualizzazione differenti di dati indentici, questa caratteristica e' molto utilile quando, ad esempio, dobbiamo visualizzare un'applicazione su dispositivi con monitor a risoluzione differente.
MainWindow1.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace WpfDifferentXAMLinSameViewModel
{
///
/// Interaction logic for MainWindow1.xaml
///
public partial class MainWindow1 : Window
{
public MainWindow1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Posso caricare Page1.xaml o Page2.xaml
StreamReader mysr = new StreamReader("Page2.xaml");
Page page = XamlReader.Load(mysr.BaseStream) as Page;
page.DataContext = new ViewModel();
Content = page;
}
}
}
ViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Input;
namespace WpfDifferentXAMLinSameViewModel
{
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private ICommand m_myCommand;
private String m_myProp1 = "Prop1";
public ViewModel()
{
MyCommand = new RelayCommand(new Action<object>(ShowMessage));
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
PropertyChanged(this, e);
}
public String MyProp1
{
get { return m_myProp1; }
set
{
if (m_myProp1 != value)
{
m_myProp1 = value;
OnPropertyChanged(new PropertyChangedEventArgs("MyProp1"));
}
}
}
public ICommand MyCommand
{
get
{
return m_myCommand;
}
set
{
m_myCommand = value;
}
}
public void ShowMessage(object obj)
{
MyProp1 = obj.ToString();
}
}
}
WpfDifferentXAMLinSameViewModel.zip