I have a PlotView that has the height binds to the property ModelHeight in the view model.
MainWindow.xaml
<oxy:PlotView x:Name="IOPlot" Model="{Binding IOPlotModel}" Height="{Binding ModelHeight, UpdateSourceTrigger=PropertyChanged}" Width="630">
ViewModel.cs
private double modelheight = 300;
public double ModelHeight {
get{return modelheight;}
set { modelheight = value;
RaisePropertyChanged("ModelHeight");
RaisePropertyChanged("IOPlotModel");
this.IOPlotModel.InvalidatePlot(false);
}
}
The problem is that: it doesn't update the height with the data binding! The height only changes once during the startup of the PlotModel. It seems like the height is fixed (IOPlotModel.Height always equals 300 even though ModelHeight changed).
Does anyone know how to fix this issue?
In this minimal example view and view model are the same class MainWindow, so the DataContext is set to this inside the constructor. Usually it should be the view model in a MVVM architecture.
XAML:
<Window x:Class="PlotTest.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:oxyplot="http://oxyplot.org/wpf"
mc:Ignorable="d"
Title="MainWindow"
Height="450"
Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBox x:Name="HeightTextBox"
Width="200"
TextChanged="HeightTextBox_TextChanged" />
<oxyplot:PlotView Grid.Row="1"
Model="{Binding MyModel, UpdateSourceTrigger=PropertyChanged}"
Height="{Binding ModelHeight, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
</Window>
Code behind:
using OxyPlot;
using System.ComponentModel;
using System.Windows;
namespace PlotTest
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
private double modelheight = 300;
public MainWindow()
{
this.DataContext = this;
this.MyModel = new PlotModel() { Background = OxyColors.AliceBlue };
InitializeComponent();
}
public event PropertyChangedEventHandler PropertyChanged;
public double ModelHeight
{
get { return modelheight; }
private set
{
modelheight = value;
this.RaisePropertyChanged("ModelHeight");
}
}
public PlotModel MyModel { get; private set; }
private void HeightTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
if (double.TryParse(this.HeightTextBox.Text, out double height))
{
this.ModelHeight = height;
}
}
private void RaisePropertyChanged(string propertyName = "")
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Related
I would like to ask a question regarding the UI update of a WPF application based on changes applied to MVVM objects stored in a ObservableCollection. But first, let me explain my intuition.
I have the following files created to support my Project Solution. In total there are 5 files, so I present their code for you to replicate the issue. Copy-paste the code below in a new Solution project (WPF - .NET Core) and see for yourself my issue.
File 1: App.xaml
<Application x:Class="WpfAppTestingScenarios.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfAppTestingScenarios"
StartupUri="Window1.xaml">
<Application.Resources>
</Application.Resources>
</Application>
File 2: Window1.xaml
<Window x:Class="WpfAppTestingScenarios.Window1"
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:WpfAppTestingScenarios"
d:DataContext="{d:DesignInstance Type=local:LoginScreenViewModel}"
mc:Ignorable="d"
Title="Window1"
Height="450"
Width="800">
<Grid>
<Button Content="Click me"
Command="{Binding Path=LoginCommand}"
Height="20"
Width="110"/>
</Grid>
</Window>
File 3: MainWindow.xaml
<Window x:Class="WpfAppTestingScenarios.MainWindow"
x:Name="MainWindowName"
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:WpfAppTestingScenarios"
d:DataContext="{d:DesignInstance Type=local:MainWindowViewModel}"
mc:Ignorable="d"
Title="MainWindow"
Height="450"
Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="640"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="225"/>
<RowDefinition Height="210"/>
</Grid.RowDefinitions>
<StackPanel
x:Name="StackPanel1"
Visibility="{Binding StackPanelVisibility1}"
Grid.Row="0"
Grid.Column="1">
<TextBlock Text="Hello World 1"/>
</StackPanel>
<Button
IsEnabled="{Binding Path=EnableViewButton1, UpdateSourceTrigger=PropertyChanged, FallbackValue=false}"
Content="View"
Width="80"
Height="25"
FontSize="10"
FontWeight="Light"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Grid.Row="0"
Grid.Column="1">
</Button>
<StackPanel
x:Name="StackPanel2"
Visibility="{Binding StackPanelVisibility2}"
Grid.Row="1"
Grid.Column="1">
<TextBlock Text="Hello World 2"/>
</StackPanel>
<Button
IsEnabled="{Binding Path=EnableViewButton2}"
Content="View"
Width="80"
Height="25"
FontSize="10"
FontWeight="Light"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Grid.Row="1"
Grid.Column="1">
</Button>
</Grid>
</Window>
File 4: Window1.xaml.cs
using Prism.Commands;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
namespace WpfAppTestingScenarios
{
public class LoginScreenViewModel : INotifyPropertyChanged
{
public ICommand LoginCommand
{
get { return new DelegateCommand<object>(FuncLoginCommand); }
}
public void FuncLoginCommand(object parameters)
{
MainWindow WindMain = new MainWindow();
WindMain.Show();
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string property)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
}
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
DataContext = new LoginScreenViewModel();
}
}
}
File 5: MainWindow.xaml.cs
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
namespace WpfAppTestingScenarios
{
public class MyCustomClass : INotifyPropertyChanged
{
public string Key { get; set; }
private object _value;
public object Value
{
get { return _value; }
//set { _value = value; NotifyPropertyChanged($"{Value}"); }
//change to
set { _value = value; NotifyPropertyChanged(nameof(Value)); } //still no luck
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class MainWindowViewModel : INotifyPropertyChanged
{
//1. - StackPanelVisibility 1
private Visibility _StackPanelVisibility1;
public Visibility StackPanelVisibility1
{
get
{
return _StackPanelVisibility1;
}
set
{
_StackPanelVisibility1 = value;
OnPropertyChanged("StackPanelVisibility1");
}
}
//2. - StackPanelVisibility 2
private Visibility _StackPanelVisibility2;
public Visibility StackPanelVisibility2
{
get
{
return _StackPanelVisibility2;
}
set
{
_StackPanelVisibility2 = value;
OnPropertyChanged("StackPanelVisibility2");
}
}
//3. - EnableViewButoon 1
private bool _EnableViewButton1;
public bool EnableViewButton1
{
get
{
return _EnableViewButton1;
}
set
{
_EnableViewButton1 = value;
OnPropertyChanged("EnableViewButton1");
}
}
//4. - EnableViewButoon 2
private bool _EnableViewButton2;
public bool EnableViewButton2
{
get
{
return _EnableViewButton2;
}
set
{
_EnableViewButton2 = value;
OnPropertyChanged("EnableViewButton2");
}
}
private void CustomFunction(ObservableCollection<MyCustomClass> UICollection)
{
if ((Visibility)UICollection[0].Value == Visibility.Hidden)
UICollection[0].Value = Visibility.Visible;
if ((bool)UICollection[1].Value == false)
UICollection[1].Value = true;
}
public MainWindowViewModel()
{
ObservableCollection<MyCustomClass> dict = new ObservableCollection<MyCustomClass>
{
new MyCustomClass { Key = "StackPanelVisibility", Value = StackPanelVisibility1 },
new MyCustomClass { Key = "EnableViewButton", Value = EnableViewButton1 }
};
CustomFunction(dict);
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string property)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
}
}
So even though everything was set successfully and with no errors, when I run the application and I click the button Click me the UI and thus the objects of the MainWindow are not updated.
Initially, I tried this logic with Dictionaries. But then I read that Dictionary cannot update the UI of a WPF application so I changed it to an ObservableCollection. However, both approaches didn't work for me.
Edit
Based on this answer, I created the following code
public class MyCustomClass : INotifyPropertyChanged
{
public string Key { get; set; }
private object _value;
public object Value
{
get { return _value; }
//set { _value = value; NotifyPropertyChanged($"{Value}"); }
//change to
set { _value = value; NotifyPropertyChanged(nameof(Value)); } //still no luck
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
But still, I don't observe any UI change.
My end result would be to enable the two buttons in the MainWindow like in the screen below (when I click the button Click me)
Image of my desired result
I have a MainWindowViewModel and my MainWindow contains a frame to display project pages.
The first page being displayed is a list of recently opened projects(Similar to Microsoft word) which has it's own ViewModel.
There is no problem in loading the list but when I want to send the user-selected item from this list to the MainWindowViewModel I can not use Find-Ancestor to reach the Window DataContext(It looks like the frame has some restrictions).
How can I send the user-selected item to the MainWindowViewModel?
public class RecentlyOpenedFilesViewModel
{
readonly IFileHistoryService _fileHistoryService;
private ObservableCollection<RecentlyOpenedFileInfo> _RecentlyOpenedFilesList;
public ObservableCollection<RecentlyOpenedFileInfo> RecentlyOpenedFilesList
{
get { return _RecentlyOpenedFilesList; }
set { _RecentlyOpenedFilesList = value; RaisePropertyChanged(); }
}
public RecentlyOpenedFilesViewModel( IFileHistoryService fileService):base()
{
_fileHistoryService = fileService;
RecentlyOpenedFilesList=new ObservableCollection<RecentlyOpenedFileInfo>(_fileHistoryService.GetFileHistory());
}
public void RefreshList()
{
RecentlyOpenedFilesList = new ObservableCollection<RecentlyOpenedFileInfo>(_fileHistoryService.GetFileHistory());
}
}
<Page
x:Class="MyProject.Views.V3.Other.RecentlyOpenedFilesPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyProject.Views.V3.Other"
xmlns:vmv3="clr-namespace:MyProject"
Title="RecentlyOpenedFilesPage">
<Page.Resources>
<DataTemplate x:Key="RecentlyOpenedFileInfoTemplate"
>
<Button
Height="70"
Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}, Path=DataContext.OpenProjectFromPathCommand}"
CommandParameter="{Binding}">
<Button.Content>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="70" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="200" />
</Grid.ColumnDefinitions>
<StackPanel
Grid.Row="0"
Grid.Column="0"
VerticalAlignment="Top">
<TextBlock Text="{Binding Name}" />
<TextBlock Text="{Binding Path}" />
</StackPanel>
<TextBlock
Grid.Row="0"
Grid.Column="1"
Margin="50,0,0,0"
VerticalAlignment="Center"
Text="{Binding DateModified}" />
</Grid>
</Button.Content>
</Button>
</DataTemplate>
</Page.Resources>
<Grid>
<ListView
ItemTemplate="{StaticResource RecentlyOpenedFileInfoTemplate}"
ItemsSource="{Binding RecentlyOpenedFilesList}" />
</Grid>
public RecentlyOpenedFilesPage(MainWindowViewModel vm)
{
this.DataContext = vm;
InitializeComponent();
}
Now I have a direct link between MainWindowViewModel and RecentlyOpenedFilesViewModel but I would like to remove this dependency and use another way of connection like(routed commands which I have a problem with)
The MainWindow contains a frame in which the RecentlyOpenedFilesPage is set to its content.
<Window
x:Class="MyProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:fw="clr-namespace:SourceChord.FluentWPF;assembly=FluentWPF" >
<Frame Name="frameMain"/></Window>
public class MainWindowViewModel : RecentlyOpenedFilesViewModel, IMainWindowViewModel
{
private void LoadRecentlyOpenedProjects()
{
CurrentView = new RecentlyOpenedFilesPage(this);
}
}
So, here is my suggested solution. It uses the basic idea to propagate the DataContext from the outside into a frame content, as presented in page.DataContext not inherited from parent Frame?
For demonstration purpose, I provide an UI with a button to load the page, a textblock to display the selected result from the list within the page and (ofcourse) the frame that holds the page.
<Window x:Class="WpfApplication1.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"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid Name="parentGrid">
<TextBlock VerticalAlignment="Top" HorizontalAlignment="Right" Margin="5" Text="{Binding SelectedFile}" Width="150" Background="Yellow"/>
<Button VerticalAlignment="Top" HorizontalAlignment="Left" Margin="5" Click="Button_Click" Width="150">Recent Files List</Button>
<Frame Name="frameMain" Margin="5 50 5 5"
LoadCompleted="frame_LoadCompleted"
DataContextChanged="frame_DataContextChanged"/>
</Grid>
</Window>
Viewmodel classes:
public class BaseVm : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName]string propName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
}
public class MyWindowVm : BaseVm
{
private string _selectedFile;
public string SelectedFile
{
get => _selectedFile;
set
{
_selectedFile = value;
OnPropertyChanged();
}
}
}
public class MyPageVm : BaseVm
{
public ObservableCollection<MyRecentFile> Files { get; } = new ObservableCollection<MyRecentFile>();
}
public class MyRecentFile
{
public string Filename { get; set; }
public string FilePath { get; set; }
}
Main code behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
parentGrid.DataContext = new MyWindowVm();
}
// Load Page on some event
private void Button_Click(object sender, RoutedEventArgs e)
{
frameMain.Content = new RecentlyOpenedFilesPage(new MyPageVm
{
Files =
{
new MyRecentFile { Filename = "Test1.txt", FilePath = "FullPath/Test1.txt"},
new MyRecentFile { Filename = "Test2.txt", FilePath = "FullPath/Test2.txt"}
}
});
}
// DataContext to Frame Content propagation
private void frame_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
UpdateFrameDataContext(sender as Frame);
}
private void frame_LoadCompleted(object sender, NavigationEventArgs e)
{
UpdateFrameDataContext(sender as Frame);
}
private void UpdateFrameDataContext(Frame frame)
{
var content = frame.Content as FrameworkElement;
if (content == null)
return;
content.DataContext = frame.DataContext;
}
}
Now, the page.xaml ... notice: we will set the page viewmodel to the pageRoot.DataContext, not to the page itself. Instead we expect the page datacontext to be handled from the outside (as we do in the MainWindow) and we can reference it with the page internal name _self:
<Page x:Class="WpfApplication1.RecentlyOpenedFilesPage"
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"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="RecentlyOpenedFilesPage"
Name="_self">
<Grid Name="pageRoot">
<ListView ItemsSource="{Binding Files}"
SelectedValue="{Binding DataContext.SelectedFile,ElementName=_self}"
SelectedValuePath="FilePath"
DisplayMemberPath="Filename"/>
</Grid>
</Page>
Page code behind to wire up the viewmodel:
public partial class RecentlyOpenedFilesPage : Page
{
public RecentlyOpenedFilesPage(MyPageVm myPageVm)
{
InitializeComponent();
pageRoot.DataContext = myPageVm;
}
}
As you can see, with this setup, no viewmodel knows about any involved view. The page doesn't handle the MainViewmodel, but the page requires a DataContext with a SelectedFile property to be provided from the outside.
The MainViewmodel doesn't know about the recent file list, but allows to set a selected file, no matter where it originates from.
The decision, to initialize the RecentlyOpenedFilesPage with a pre-created viewmodel is not important. You could just as well use internal logic to initialize the page with recent files, then the Mainwindow would not be involved.
Here is the method:
private void Capitales_SelectedChanged(object sender, RoutedEventArgs e)
{
string s = Capitales.SelectedItem.ToString();
tb.Text = "Selection: " + s;
}
I'm putting a list in the combobox, and when I compile the program, the textbox shows the next: ComboBox_MicroDocu.MainWindow+Ciudades, where "Ciudades" references my class.
You are writing WPF app as you whould do with Winform. This whould work, but there is a better way to do it. Use MVVM (Model View ViewModel).
MVVM is great since it allows you to decouple your views (xaml) from your business logic (viewModels). It's also great for testability.
Check out some good resources here https://www.tutorialspoint.com/mvvm/index.htm
this is how your code should looks like :
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" >
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ComboBox Grid.Column="0" ItemsSource="{Binding Elements}" SelectedItem="{Binding SelectedElement}"/>
<TextBox Grid.Column="1" Text="{Binding SelectedElement}"/>
</Grid>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
ViewModel.cs
public class ViewModel : INotifyPropertyChanged
{
private string _selectedElement;
public IEnumerable<string> Elements
{
get
{
for(int i = 0; i < 10; i++)
{
yield return $"Element_{i}";
}
}
}
public string SelectedElement
{
get
{
return _selectedElement;
}
set
{
_selectedElement = value;
RaisePropertyChanged();
}
}
private void RaisePropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
First, this is a simplified version from a wizard control using MVVM. The problem is just easier to reproduce as described below
After much narrowing down, I have resolved an infinite exception in my code to be due to the WPF ContentControl. However, I have yet to figure out how to handle it, other than try-catch wrapping all of my possible instantiation code. Here is sample code that reproduces this...any help on how to keep this infinite exception from occurring would be greatly appreciated.
Additional Details
To sum up, the problem is that if the content control changes its contents, and the thing being loaded in throws an exception, then it will throw, then retry the load, causing the throw again and again.
MainWindow.xaml
<Window x:Class="WpfApplication8.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Name ="Main">
<Grid>
<ContentControl Name="bar" Content="{Binding ElementName=Main, Path=foo}"/>
<Button Click="ButtonBase_OnClick" Margin="20" Width="50"/>
</Grid>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window, INotifyPropertyChanged
{
private UserControl _foo;
public UserControl foo
{
get { return _foo; }
set { _foo = value; OnPropertyChanged("foo"); }
}
public MainWindow()
{
InitializeComponent();
foo = new UserControl1();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
foo = new UserControl2();
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
UserControl1 is blank and all default
UserControl2.xaml.cs
public UserControl2()
{
InitializeComponent();
throw new Exception();
}
Do not bind ContentControl to MainWindow. Instead use DataTemplates to select the content for the MainWindow. One example-contrived way of doing it is to bind the ContentControl's Content to the DataContext of the MainWindow.
First some observable test data is needed. The specifics of this data are not important. The main point is to have two different classes of test data from which to choose - TestData.cs:
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace fwWpfDataTemplate
{
// Classes to fill TestData
public abstract class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("Name");
}
}
}
public class Student : Person { }
public class Employee : Person
{
float _salary;
public float Salary
{
get { return _salary; }
set
{
_salary = value;
OnPropertyChanged("Salary");
}
}
}
public class TestData : ObservableCollection<Person>
{
public TestData()
: base(new List<Person>()
{
new Student { Name = "Arnold" },
new Employee { Name = "Don", Salary = 100000.0f }
}) { }
}
}
Then add DataTemplates to MainWindow's resources - MainWindow.xaml:
<Window x:Class="fwWpfDataTemplate.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:me="clr-namespace:fwWpfDataTemplate"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="{x:Type me:Student}">
<StackPanel>
<TextBlock Text="Student"/>
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type me:Employee}">
<StackPanel>
<TextBlock Text="Employee"/>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="Salary"/>
<TextBlock Text="{Binding Salary}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Button Content="Change Data Context" Click="Button_Click" />
<ContentControl Grid.Row="1" Content="{Binding}"/>
</Grid>
</Window>
Note: instead of the StackPanels the contents of the DataTemplates could be UserControl1, UserControl2, etc.
Then add some code to change the data context - MainWindow.cs:
using System.Windows;
namespace fwWpfDataTemplate
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
TestData testData = new TestData();
int testIndex = -1;
private void Button_Click(object sender, RoutedEventArgs e)
{
testIndex = (testIndex + 1) % testData.Count;
this.DataContext = testData[testIndex];
}
}
}
Enjoy.
I have recently started using WPF and MVVM approach. I ma getting a problem in the following case. Can someone help me on this?
I have a list box in my MainWindow.xaml. I am trying to load the different user controls for each list box item selection. My MainWindow.xaml looks like below.
MainWindow.xaml
<Window x:Class="MoreOnBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MoreOnBinding"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.Resources>
<DataTemplate DataType="{x:Type local:UserControl1VM}">
<local:UserControl1/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:UserControl2VM}">
<local:UserControl2/>
</DataTemplate>
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<ListBox Grid.Column="0" ItemsSource="{Binding ViewModelsCollection}" DisplayMemberPath="ViewModelName" SelectedValue="{Binding SelectedViewModel}" IsSynchronizedWithCurrentItem="True"/>
<ContentControl Grid.Column="1" Content="{Binding SelectedViewModel.ViewModel}"/>
</Grid>
</Window>
My MainWidnow View model is as below.
MainWindowVM
public class MainWindowVM : ViewModelBase
{
public MainWindowVM()
{
this.ViewModelsCollection = new ObservableCollection<ViewModelInfo>(new List<ViewModelInfo>()
{
new ViewModelInfo("Control1", new UserControl1VM()),
new ViewModelInfo("Control2", new UserControl2VM()),
});
}
private ObservableCollection<ViewModelInfo> viewModelsCollection;
public ObservableCollection<ViewModelInfo> ViewModelsCollection
{
get { return viewModelsCollection; }
set
{
if (viewModelsCollection != value)
{
viewModelsCollection = value;
RaisePropertyChanged(() => ViewModelsCollection);
this.SelectedViewModel = this.ViewModelsCollection[0];
}
}
}
private ViewModelInfo selectedViewModel;
public ViewModelInfo SelectedViewModel
{
get { return selectedViewModel; }
set
{
if (selectedViewModel != value)
{
selectedViewModel = value;
RaisePropertyChanged(() => SelectedViewModel);
}
}
}
}
public class ViewModelInfo : ViewModelBase
{
public ViewModelInfo(string viewModelName, ViewModelBase viewModel)
{
this.ViewModelName = viewModelName;
this.ViewModel = viewModel;
}
private string viewModelName;
public string ViewModelName
{
get { return viewModelName; }
set
{
if (viewModelName != value)
{
viewModelName = value;
RaisePropertyChanged(() => ViewModelName);
}
}
}
private ViewModelBase viewModel;
public ViewModelBase ViewModel
{
get { return viewModel; }
set
{
if (viewModel != value)
{
viewModel = value;
RaisePropertyChanged(() => ViewModel);
}
}
}
}
Each user control has a text box in it. The user control xaml and viewmodels are as below.
UserControl1
<UserControl x:Class="MoreOnBinding.UserControl1"
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:MoreOnBinding"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Text="User Control 1"/>
<TextBox Grid.Row="2" Text="{Binding UC1Text}" Width="100" Height="30"/>
</Grid>
</UserControl>
UserControl1VM
public class UserControl1VM : ViewModelBase
{
private string uC1Text;
public string UC2Text
{
get { return uC1Text; }
set
{
if (uC1Text != value)
{
uC1Text = value;
RaisePropertyChanged(() => UC2Text);
}
}
}
}
The user control1 code file is as below
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
}
The UserControl 2 is same as the user control1 only the name change.
Now coming to my problem, after running the application I clicked the first item of the list box and it loaded the UserControl1 on ContentControl. I have enntered some text say "UC1" in the text box displayed. However if click on the second item of the listbox and agian click on the first item, the text I have entered is lost. I want to retain old text. Can someone look into this and help me out?
You have a typo: data source property is UserControl1VM.UC2Text, and the binding is to UC1Text. If you'll look at output window, you'll see a binding error.