Hi i am trying to display usercontrol Dynamically But it is not working ...please help me to improve code . In cunstructor of MainWindowViewModel i tried to set initial property of contentcontrol. Thank you in advance
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:VM="clr-namespace:WpfApplication1.ViewModel"
xmlns:View="clr-namespace:WpfApplication1.View"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="{x:Type VM:FirstControlViewModel}">
<View:FirstControl></View:FirstControl>
</DataTemplate>
<DataTemplate DataType="{x:Type VM:SecondControlViewModel}">
<View:SecondControl></View:SecondControl>
</DataTemplate>
</Window.Resources>
<Grid>
<ContentControl Content="{Binding LoadedControl}" />
</Grid>
</Window>
View Model Code :-
public class MainViewModel: INotifyPropertyChanged
{
public MainViewModel()
{
LoadedControl = "FirstControlViewModel";// here i am setting property
//But not working
}
private string _LoadedControl;
public string LoadedControl
{
get { return _LoadedControl; }
set { _LoadedControl = value;
NotifyPropertyChanged("LoadedControl");
}
}
You need to set LoadedControl
to an instance of your ViewModel type, not a string!
public MainViewModel()
{
LoadedControl = new FirstControlViewModel();
}
private ViewModelBase _LoadedControl;
public ViewModelBase LoadedControl
{
get { return _LoadedControl; }
set { _LoadedControl = value;
NotifyPropertyChanged("LoadedControl");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.