Add a usercontrol to caliburm micro dynamically - c#

I am using Caliburn Micro with WPF. I want to create an application with a menu on the left side, and a grid on the right side of the application. When clicking on a menu item, the grid on the right side, will change to another view. The another view will be in a separate file.
MainWindowView:
<UserControl x:Class="CMDemo.Views.MainWindowView"
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="300" d:DesignWidth="300">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="90*" />
<ColumnDefinition Width="210*" />
</Grid.ColumnDefinitions>
<StackPanel Name="LeftMenu">
<Button Name="ChangeDisplay" Content="Click Me"></Button>
<TextBlock x:Name="MyString"></TextBlock>
</StackPanel>
<Grid Grid.Column="1" x:Name="MainGridContent" />
</Grid>
MainWindowViewModel:
public class MainWindowViewModel : PropertyChangedBase
{
private UserControl mainGridContent;
private string myString;
public UserControl MainGridContent
{
get { return this.mainGridContent; }
set
{
this.mainGridContent = value;
NotifyOfPropertyChange(() => this.MainGridContent);
}
}
public string MyString
{
get { return this.myString; }
set
{
this.myString = value;
NotifyOfPropertyChange(() => this.MyString);
}
}
public void ChangeDisplay()
{
this.MainGridContent = new ChangeDisplayView();
this.MyString = "Testing....";
}
}
The changeDisplayViewModel:
public class changeDisplayViewModel: PropertyChangedBase
{
}
The changeDisplayView:
<UserControl x:Class="CMDemo.Views.changeDisplayView"
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="300" d:DesignWidth="300">
<Grid>
<TextBox content="Hello Caliburn Micro">
</Grid>
When I click the "Click Me" button the TextBlock "MyString" is updated and showing, but the usercontrol is not. What am I doing wrong?

Try changing MainGridContent to a changeDisplayViewModel rather than the view itself.

Related

ContentControl not refreshing View when new ViewModel is created

I am trying to make an app using using MVVMLight that has a sidebar with buttons, each button shows a new usercontrol hosted in a ContentControl. When the user clicks the buttons in the sidebar (Show View1 / Show View2) it shows the views correctly.
My problems arise when the user has already shown a View (it could be View1 or View2 ), say View1 and click (Show View1) ** again ** View1 controls remain with the same values and I would like to show the same view with all controls as if it had restarted. (I know that I could reset all controls within the user control (View1) but my application requires having a new instance of the view every time the button is clicked).
Somehow, in the same scenario when the user is in View 1, switch to view 2 and return to view 1, a new instance is created and shown as I would like. I would like to get the same result without the need to switch to view 2 and return.
Here is a minimal reproducible example of the issue:
ViewModelLocator.cs
using CommonServiceLocator;
using GalaSoft.MvvmLight.Ioc;
namespace SidebarApp.ViewModel
{
public class ViewModelLocator
{
/// <summary>
/// Initializes a new instance of the ViewModelLocator class.
/// </summary>
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
// Register viewmodels
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<View1ViewModel>();
SimpleIoc.Default.Register<View2ViewModel>();
}
public MainViewModel Main { get { return ServiceLocator.Current.GetInstance<MainViewModel>(); } }
public View1ViewModel View1Vm { get { return ServiceLocator.Current.GetInstance<View1ViewModel>(); } }
public View2ViewModel View2Vm { get { return ServiceLocator.Current.GetInstance<View2ViewModel>(); } }
public static void Cleanup()
{
// TODO Clear the ViewModels
}
}
}
MainViewModel.cs
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System.Windows.Input;
namespace SidebarApp.ViewModel
{
public class MainViewModel : ViewModelBase
{
// Commands
public ICommand ShowView1Command { get; private set; }
public ICommand ShowView2Command { get; private set; }
/// <summary>
/// Property that will cointain the current viewmodel to show
/// ViewModelBase inplements ObservableObject class which imlements INotifyPropertyChanged
/// </summary>
public ViewModelBase CurrentViewModel { get; set; }
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
this.ShowView1Command = new RelayCommand(ShowView1);
this.ShowView2Command = new RelayCommand(ShowView2);
}
private void ShowView1()
{
// I tried this but it doesn't work
//CurrentViewModel = null or View2ViewModel;
CurrentViewModel = new View1ViewModel();
}
private void ShowView2()
{
CurrentViewModel = new View2ViewModel();
}
}
}
MainWindow.xaml
<Window x:Class="SidebarApp.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:SidebarApp"
mc:Ignorable="d"
DataContext="{Binding Main, Source={StaticResource Locator}}"
Title="MainWindow" Height="348.965" Width="560.683">
<Window.Resources>
<DataTemplate DataType="{x:Type local:View1ViewModel}">
<local:View1View />
</DataTemplate>
<DataTemplate DataType="{x:Type local:View2ViewModel}">
<local:View2View />
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.3*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackPanel>
<Button Command="{Binding ShowView1Command}">Show View1</Button>
<Button Command="{Binding ShowView2Command}">Show View2</Button>
</StackPanel>
<ContentControl Grid.Column="1" Content="{Binding Path=CurrentViewModel}"></ContentControl>
</Grid>
</Window>
View1View.xaml
<UserControl x:Class="SidebarApp.View1View"
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:SidebarApp"
mc:Ignorable="d"
DataContext="{Binding View1Vm, Source={StaticResource Locator}}"
d:DesignHeight="450" d:DesignWidth="800">
<Grid Background="LightPink">
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock HorizontalAlignment="Center" Text="Welcome to View 1" FontSize="20"/>
<TextBox HorizontalAlignment="Stretch" Text="Original text value"/>
<CheckBox Content="Some boolean value"/>
</StackPanel>
</Grid>
</UserControl>
View1ViewModel.cs
using GalaSoft.MvvmLight;
namespace SidebarApp
{
public class View1ViewModel : ViewModelBase
{
public View1ViewModel()
{
}
}
}
View2View.xaml
<UserControl x:Class="SidebarApp.View2View"
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:SidebarApp"
mc:Ignorable="d"
DataContext="{Binding View2Vm, Source={StaticResource Locator}}"
d:DesignHeight="450" d:DesignWidth="800">
<Grid Background="LightCyan">
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock HorizontalAlignment="Center" Text="Welcome to View 2" FontSize="20"/>
<TextBox HorizontalAlignment="Stretch" Text="Some text in view2"/>
<Button Content="Button"/>
</StackPanel>
</Grid>
</UserControl>
View2ViewModel.cs
using GalaSoft.MvvmLight;
namespace SidebarApp
{
public class View2ViewModel : ViewModelBase
{
public View2ViewModel()
{
}
}
}
App.xaml
<Application x:Class="SidebarApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:SidebarApp" StartupUri="MainWindow.xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" d1p1:Ignorable="d" xmlns:d1p1="http://schemas.openxmlformats.org/markup-compatibility/2006">
<Application.Resources>
<ResourceDictionary>
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" xmlns:vm="clr-namespace:SidebarApp.ViewModel" />
</ResourceDictionary>
</Application.Resources>
</Application>
For example I enter to the view1 and change the value of the textbox ("Original text value") to another value and I click again in Show View1 the text and everything in the usercontrol stays the same but when I switch to view2 and go back to view1 a new usercontrol is shown with his original values.
This might feel like something of a workaround, but it works. Hopefully it will prove useful. (Obviously make same changes to View2View view/view model).
ViewModelLocator.cs
public View1ViewModel View1Vm { get { return new View1ViewModel(); } }
MainViewViewModel.cs
private void ShowView1()
{
CurrentViewModel = new ViewModelLocator().View1Vm;
}
View1View.xaml
<UserControl x:Class="SidebarApp.View1View"
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:SidebarApp"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid Background="LightPink">
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock HorizontalAlignment="Center" Text="Welcome to View 1" FontSize="20"/>
<TextBox HorizontalAlignment="Stretch" Text="{Binding Path=View1Text, Mode=TwoWay}"/>
<CheckBox Content="Some boolean value" IsChecked="{Binding Path=CheckBoxChecked, Mode=TwoWay}"/>
</StackPanel>
</Grid>
</UserControl>
View1ViewModel.cs
public class View1ViewModel : ViewModelBase
{
private string _view1Text;
private bool _checkBoxedChecked;
public string View1Text
{
get
{
return _view1Text;
}
set
{
_view1Text = value;
RaisePropertyChanged("View1Text");
}
}
public bool CheckBoxChecked
{
get
{
return _checkBoxedChecked;
}
set
{
_checkBoxedChecked = value;
RaisePropertyChanged("CheckBoxChecked");
}
}
public View1ViewModel()
{
View1Text = "Original text value";
}
}

WPF Binding TabControl TabItem

I am relatively new to MVVM in WPF and have been trying to solve an issue for several days now. I am using the dragablz tab control and binding the ItemsSource which is an ObservableList of objects. The content of the Tab Item is a UserControl, however; its datacontext is null. I've created a simple setup to demonstrate the issue I'm having:
Model/ViewModel Classes:
public class Item
{
public string Header { get; set; }
public ItemContent Body { get; set; }
}
public class ItemContent
{
public string Name { get; set; }
public string Description { get; set; }
}
class MainWindowViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName]string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public ObservableCollection<Item> Items { get; set; }
}
Main Window XAML
<Window x:Class="WpfTestApplication.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:WpfTestApplication"
xmlns:views="clr-namespace:WpfTestApplication.ViewModels"
xmlns:dragablz="clr-namespace:Dragablz;assembly=Dragablz"
xmlns:dockablz="clr-namespace:Dragablz.Dockablz;assembly=Dragablz"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<views:MainWindowViewModel />
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<Button Name="btnAdd" Content="Add" Click="btnAdd_Click" />
<dockablz:Layout Grid.Row="1">
<dragablz:TabablzControl HeaderMemberPath="Header" ItemsSource="{Binding Items}" SelectedIndex="1">
<dragablz:TabablzControl.ContentTemplate>
<DataTemplate DataType="{x:Type views:Item}">
<local:TabItemControl />
</DataTemplate>
</dragablz:TabablzControl.ContentTemplate>
</dragablz:TabablzControl>
</dockablz:Layout>
</Grid>
</Window>
Tab Item XAML
<UserControl x:Class="WpfTestApplication.TabItemControl"
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:WpfTestApplication"
xmlns:views="clr-namespace:WpfTestApplication.ViewModels"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.DataContext>
<views:ItemContent />
</UserControl.DataContext>
<Grid>
<TextBox Text="{Binding Body}" />
</Grid>
</UserControl>
And the btnAdd_Click event
Note that I don't use this in my actual code but it was a fast and dirty way to add tab items dynamically without adding a command.
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
((ViewModels.MainWindowViewModel)DataContext).Items.Add(new ViewModels.Item() { Header = "New One", Body = new ViewModels.ItemContent() { Name = "This One" } });
}
Will answered my question in the comment to the original question. I used his answer to another post: https://stackoverflow.com/a/44729258/1228 to do the following.
I removed this from my UserControl:
<UserControl.DataContext>
<views:ItemContent />
</UserControl.DataContext>
I then added a dependency property called Body to my UserControl code behind:
public static readonly DependencyProperty BodyProperty =
DependencyProperty.Register("Body",
typeof(ViewModels.ItemContent),
typeof(TabItemControl),
new PropertyMetadata(null));
public ViewModels.ItemContent Body
{
get
{
return (ViewModels.ItemContent)GetValue(BodyProperty);
}
set
{
SetValue(BodyProperty, value);
}
}
public string BodyText {
get
{
return Body?.Name;
}
set
{
if (Body != null)
{
Body.Name = value;
}
}
}
I updated my MainWindow's Tab control ContentTemplate as such:
<dragablz:TabablzControl.ContentTemplate>
<DataTemplate DataType="{x:Type views:ItemContent}">
<local:TabItemControl Body="{Binding Body}" />
</DataTemplate>
</dragablz:TabablzControl.ContentTemplate>
And changed my UserControl to use the BodyText property for the value of the TextBox:
<Grid x:Name="LayoutRoot">
<TextBox Text="{Binding BodyText}" />
</Grid>

Visibility of one user control to another user control

private void Button_Click(object sender, RoutedEventArgs e)
{
int selectedValue = (int)comboSelection.SelectedValue;
if (selectedValue == 8)
{
EightTiles et = new EightTiles();
this.Visibility = Visibility.Collapsed;
et.Visibility = Visibility.Visible;
}
}
My target is when the combo box selection is equal to 8 then click the button, current usercontrol get collapsed and next usercontrol(EightTiles) get visible.
But my problem is when i click the button it shows a blank page, next user control page doesn't showed, what is the problem and how i do to solve it..
Thanks
Plase both these controls as content of a main content control to xaml, and manage the second control visibility based on trigger of the first control. Here what I can suggest you:
1. XAML:
<Window x:Class="SoDataGridProjectsHelpAttempt.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:soDataGridProjectsHelpAttempt="clr-namespace:SoDataGridProjectsHelpAttempt"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ContentControl >
<ContentControl.ContentTemplate>
<DataTemplate>
<Grid>
<soDataGridProjectsHelpAttempt:MainSubControl x:Name="MainSubControl" Visibility="Visible"/>
<soDataGridProjectsHelpAttempt:SubSubControl x:Name="SubSubControl" Visibility="Collapsed"/>
</Grid>
<DataTemplate.Triggers>
<Trigger Property="Control.Visibility" Value="Collapsed" SourceName="MainSubControl">
<Setter TargetName="SubSubControl" Property="Visibility" Value="Visible"></Setter>
</Trigger>
</DataTemplate.Triggers>
</DataTemplate>
</ContentControl.ContentTemplate>
</ContentControl>
</Grid>
2. MainSubControl:
<UserControl x:Class="SoDataGridProjectsHelpAttempt.MainSubControl"
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:soDataGridProjectsHelpAttempt="clr-namespace:SoDataGridProjectsHelpAttempt"
xmlns:collections="clr-namespace:System.Collections;assembly=mscorlib"
xmlns:system="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" Visibility="{Binding IsControlVisible, Converter={StaticResource Bol2VisibilityConverter}, UpdateSourceTrigger=PropertyChanged}">
<UserControl.Resources>
<x:Array Type="system:Int32" x:Key="DecimalsArray">
<system:Int32>7</system:Int32>
<system:Int32>5</system:Int32>
<system:Int32>3</system:Int32>
<system:Int32>8</system:Int32>
</x:Array>
</UserControl.Resources>
<UserControl.DataContext>
<soDataGridProjectsHelpAttempt:MainSubViewModel/>
</UserControl.DataContext>
<StackPanel>
<ComboBox ItemsSource="{StaticResource DecimalsArray}"
Width="Auto"
SelectedItem="{Binding SelectedComboItem}"/>
<Button Command="{Binding Command}">Press me!!!</Button>
</StackPanel>
3. MainSubControl ViewModel:
public class MainSubViewModel : BaseObservableObject
{
private int _selectedComboItem;
private ICommand _command;
private bool _isControlVisible;
public MainSubViewModel()
{
IsControlVisible = true;
}
public ICommand Command
{
get { return _command ?? (_command = new RelayCommand(CommandMethod)); }
}
private void CommandMethod()
{
if (SelectedComboItem == 8)
IsControlVisible = false;
}
public bool IsControlVisible
{
get { return _isControlVisible; }
set
{
_isControlVisible = value;
OnPropertyChanged();
}
}
public int SelectedComboItem
{
get { return _selectedComboItem; }
set
{
_selectedComboItem = value;
OnPropertyChanged();
}
}
}
4. SecondSubControl:
<UserControl x:Class="SoDataGridProjectsHelpAttempt.SubSubControl"
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="300" d:DesignWidth="300">
<Grid>
<Image Source="2014_8_27_Bing_en-AU.jpg" Margin="50"></Image>
</Grid>
5. App.xaml (put into Application.Resources):
<BooleanToVisibilityConverter x:Key="Bol2VisibilityConverter" />
regards,
your problem is that et goes out of scope, so after the function is doesn't exist anymore. you need to create it "outside" in a scope where it will still exist before and after that function.
So for example if there's a class called Application and that class holds the current control that your Button_click is attached to, you need to create the other control there too. Or at least the et variable if you don't want to create the EightTiles until you need it.

UserControl is not displayed

EDIT: It seems like that I needed to change the height of RowDefinition. Thanks goes to Alvaro. However:
how do I reference different elements inside my usercontrol (change their properties), when I want to change them in MainWindow.xaml and MainWindow.xaml.cs?
I have two XAML files in the same namespace.
MainWindow.xaml
List.xaml
When I try to add List.xaml usercontrol to my mainwindow xaml (that is insert xaml from another file), it does not show up.
I insert usercontrol that exists in Lemosystem namespace and inside View folder.
xmlns:lemoview="clr-namespace:Lemosystem.View"
I add usercontrol to my MainWindow.xaml:
<lemoview:List/>
Nothing shows up. Here is my List XAML (code is the default):
<UserControl x:Class="Lemosystem.View.List"
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="300" d:DesignWidth="300">
<Grid>
<Label Content="What do you want to do today?" HorizontalAlignment="Left" Margin="10,96,-83,0" VerticalAlignment="Top" Height="44" Width="373" FontSize="24" FontWeight="Bold"/>
</Grid>
</UserControl>
I expect the label from my usercontrol to show up in MainWindow.xaml GUI, but it doesn't.
MainWindow.xaml
<Window x:Class="Lemosystem.View.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:lemocontroller="clr-namespace:Lemosystem.Controller"
xmlns:lemoview="clr-namespace:Lemosystem.View"
Title="{Binding Path=SystemName}" Height="603" Width="827"
ResizeMode="NoResize" WindowStartupLocation="Manual"
>
<Grid Name="Window" Margin="0,0,2,0">
<Grid.RowDefinitions>
<RowDefinition Height="0*"/>
<RowDefinition/>
</Grid.RowDefinitions>
...
<lemoview:List/>
...
</Grid>
</Window>
And how do I reference different elements inside my usercontrol (change their properties), when I want to change them in MainWindow.xaml and MainWindow.xaml.cs?
So, I created a project with :
List.Xaml
<UserControl x:Class="WpfApplication1.List"
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="300" d:DesignWidth="300">
<Grid>
<Label Content="{Binding TextToDisplay}"
HorizontalAlignment="Left"
Margin="10,96,-83,0"
VerticalAlignment="Top"
Height="44"
Width="373"
FontSize="24"
FontWeight="Bold" />
</Grid>
</UserControl>
ListViewModel.cs:
public class ListViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
private string textToDisplay;
public string TextToDisplay
{
get { return textToDisplay; }
set { textToDisplay = value; OnPropertyChanged("TextToDisplay"); }
}
public ListViewModel(string value)
{
TextToDisplay = value;
}
}
}
MainWindow.Xaml:
<Window x:Class="WpfApplication1.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"
xmlns:lemoview="clr-namespace:WpfApplication1">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Button Content="Click Me" HorizontalAlignment="Center" Click="Button_OnClick"></Button>
<ListView Grid.Row="1" ItemsSource="{Binding MyList}"></ListView>
</Grid>
</Window>
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
MyList=new ObservableCollection<ListViewModel>();
}
private ObservableCollection<ListViewModel> myList;
public ObservableCollection<ListViewModel> MyList
{
get { return myList; }
set { myList = value; }
}
private void Button_OnClick(object sender, RoutedEventArgs e)
{
MyList.Add(new ListViewModel("MyValue"));
}
}
App.xaml:
<Application x:Class="WpfApplication1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpfApplication1="clr-namespace:WpfApplication1"
StartupUri="MainWindow.xaml">
<Application.Resources>
<DataTemplate DataType="{x:Type wpfApplication1:ListViewModel}">
<wpfApplication1:List />
</DataTemplate>
</Application.Resources>
in App.xaml, I just defined the binding between List.xaml and ListViewModel.cs
the viewModel of MainWindow is itself.
after every Click on the button, a new ViewModel is created, added to the list with a defined value (you will need to modify this part, to set the value you want).
I hope it will help you ! it works for me.
How do you like to show something, if you put it il a row that has height ="0" ?
change it to :
<Window x:Class="Lemosystem.View.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:lemocontroller="clr-namespace:Lemosystem.Controller"
xmlns:lemoview="clr-namespace:Lemosystem.View"
Title="{Binding Path=SystemName}" Height="603" Width="827"
ResizeMode="NoResize" WindowStartupLocation="Manual"
>
<Grid Name="Window" Margin="0,0,2,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<lemoview:List/>
</Grid>

How to get datacontext used in another xaml

I have a test application wich consists on two Windows and a UserControl.
I want to insert the control in each Window using the same DataContext:
MainWindow.xaml:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:view="clr-namespace:WpfApplication2.View"
xmlns:viewModel="clr-namespace:WpfApplication2.ViewModel"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<viewModel:ControlColorViewModel x:Name="dataContext1"/>
</Window.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.2*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Width="64" Height="64" Command="{Binding
Path=PressedButton}">Press</Button>
<view:ControlColor Grid.Column="1" />
</Grid>
</Window>
ControlColor.xaml:
<UserControl x:Class="WpfApplication2.View.ControlColor"
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:viewModel="clr-namespace:WpfApplication2.ViewModel"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid Background="{Binding Path=BackgroundColor}">
</Grid>
</UserControl>
ControlColorViewModel.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using System.Windows.Input;
namespace WpfApplication2.ViewModel
{
class ControlColorViewModel : ViewModelBase
{
private Brush backgroundColor;
public Brush BackgroundColor
{
get { return this.backgroundColor; }
set
{
if (this.backgroundColor != value)
{
this.backgroundColor = value;
OnPropertyChanged("BackgroundColor");
}
}
}
public ICommand PressedButton { get { return new RelayCommand(param =>
this.SetPressedButton()); } }
public ControlColorViewModel()
{
}
private void SetPressedButton()
{
BackgroundColor = Brushes.Orange;
}
}
}
Window2.xaml:
<Window x:Class="WpfApplication2.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:view="clr-namespace:WpfApplication2.View"
Title="Window2" Height="300" Width="300">
<Grid>
<view:ControlColor />
</Grid>
</Window>
When the button is pressed the background in the ContentControl in the MainWindow gets orange, and i want the same for the ContentControl inserted in Window2. Using the same datacontext.
How can i get the same datacontext used in MainWindow?
Thanks in advance.
There are a lot of ways. The easy is to have a common, shared model property (CommonModel) and send it to every ViewModels.
Next step is to use EventAggregator, but to my mind it's too complicated for you..
I'm a little new to WPF (having more of a WinForms background), but if I understand correctly you could define your dataContext1 in the App file resources and then they both could reference it.
You can use something called Dependency Injection to get your controls to use the same DataContext.
Basically, you need to take it out of the XAML and 'find/resolve' your shared ControlColorViewModel in the constructor for your controls.

Categories

Resources