Databinding custom objects - wpf

public class Employee : INotifyPropertyChanged
{
// Private Properties
private string _name;
private List<string> _address;
// The Public properties for which the getters and setters are implemented appropriately (raising OnPropertyChanged event)
}
public class EmployeeRecords: ObservableCollection<Employee>
{
public bool AddEmployee(Employee employee)
{
Add(employee);
return true;
}
public bool RemoveEmployee(int index)
{
if (Count > 0)
{
RemoveAt(index); // is the same as doing 'RemoveAt(SelectedIndex);'
}
return true;
}
}
**XAML:**
<Window x:Class="EmployeeInfo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:EmployeeInfo"
Name="Page1" Height="225" Width="610"
Title="DATABINDING DEMO">
<Window.Resources>
<DataTemplate x:Key="EmployeeTemplate">
<StackPanel>
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=EmpId}"/>
<TextBlock Text="{Binding Path=Designation}"/>
</StackPanel>
</DataTemplate>
<src:EmployeeRecords x:Key="EmpInfo"/>
</Window.Resources>
<Window.DataContext>
<Binding Source="{StaticResource EmpInfo}"/>
</Window.DataContext>
<Canvas Height="190" Width="600">
<Label Name="lblName" Height="30" Width="50" Canvas.Top="0" Canvas.Left="0" >Name</Label>
<TextBox Name="txtBoxName" Height="30" Width="125" Text="{Binding Path=Name}" Canvas.Top="5" Canvas.Left="60" />
<Label Name="lblEmpId" Height="30" Width="50" Canvas.Top="40" Canvas.Left="0" >EmpId</Label>
<TextBox Name="txtBoxEmpId" Height="30" Width="50" Text="{Binding Path=EmpId}" Canvas.Top="40" Canvas.Left="60" />
<Label Name="lblDesignation" Height="30" Width="50" Canvas.Top="75" Canvas.Left="0" >Designation</Label>
<TextBox Name="txtBoxDesignation" Height="30" Width="50" Text="{Binding Path=Designation}" Canvas.Top="75" Canvas.Left="60" />
<Label Name="lblAddress" Height="30" Width="50" Canvas.Top="115" Canvas.Left="0" >Address</Label>
<TextBox Name="txtBoxAddress" Height="30" Width="50" Text="{Binding Path=Address}" Canvas.Top="115" Canvas.Left="60" />
<TextBox Name="txtBoxAddress2" Height="30" Width="50" Text="{Binding Path=Address}" Canvas.Top="115" Canvas.Left="120" />
<Button Height="30" Width="50" Canvas.Top="155" Canvas.Left="0" Content="Update" Click="UpdateButton_Click"/>
<Button Height="30" Width="50" Canvas.Top="155" Canvas.Left="60" Content="Submit" Click="SubmitButton_Click"/>
<Button Height="30" Width="50" Canvas.Top="155" Canvas.Left="120" Content="Remove" Click="RemoveButton_Click" />
<ListBox SelectedIndex="{Binding SelectedIndex}"
MouseDoubleClick="LstEmployee_MouseDoubleClick" Name="lstEmployee" Height="180" Width="190"
Canvas.Top="5" Canvas.Left="200" ItemsSource="{Binding}" ItemTemplate="{StaticResource EmployeeTemplate}"/>
<ListBox Name="listAddress" Height="180" Width="190" Canvas.Top="5" Canvas.Left="400" ItemsSource="{Binding Path=/Address}"/>
</Canvas>
</Window>
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
private EmployeeRecords _empRecords;
public MainWindow()
{
InitializeComponent();
Initialize();
lstEmployee.ItemsSource = _empRecords;
}
.
.
.
.
}
I'm trying to display all the properties of Employee in the 1st listBox and just the addresses in the 2nd ListBox. Can someone tell me what i'm doing wrong here?
Since I can't explicitly access the Employee object within EmployeeRecords, how can I bind the Address list inside of Employee to a control?
Thanks in advance!
Shanks

Assuming that you want to display the address of the selected Employee in the second ListBox, the following should work.
<ListBox Grid.Row="1" Name="listAddress" Height="180" Width="190" Canvas.Top="5" Canvas.Left="400" ItemsSource="{Binding ElementName=lstEmployee, Path=SelectedItem.Address}"/>
Note:
I have assumed that the public property name for the backing field private List<string> _address; is Address

Related

commands in the child ViewModel not working after navigation in mvvm app

iam working on desktop wpf MVVM app contain one MainWindow containing content control that make navigation for diffrent UserControls .
commands of the MainViewModel in the MainWindow working well.
but commands of the navigated ViewModels not working.
the code of the app.cs:
navigationStore is the store for the navigated viewModels
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
NavigationStore navigationStore = new NavigationStore();
navigationStore.CurrentViewModel = new MainBackGroundVM();
MainWindow = new MainWindow()
{
///inistiation of the main with passing the CurrentViewModel to the mainVM
DataContext = new MainVM(navigationStore)
};
MainWindow.Show();
base.OnStartup(e);
}
}
the code of MainVM
NavigateUsersCommand working well and navigate for usersVM
class MainVM :Utilities.ViewModelBase
{
private readonly NavigationStore _navigationStore;
public ViewModelBase CurrentViewModel => _navigationStore.CurrentViewModel;
public ICommand NavigateUsersCommand { get; }
public MainVM(NavigationStore navigationStore)
{
_navigationStore = navigationStore;
_navigationStore.CurrentViewModelChanged += _navigationStore_CurrentViewModelChanged;
NavigateUsersCommand = new NavigateUsersCommand(navigationStore);
}
private void _navigationStore_CurrentViewModelChanged()
{
OnPropertyChanged(nameof(CurrentViewModel));
}
}
the code for MainWindow.xml
<Window x:Class="Yakout.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:fa="http://schemas.fontawesome.io/icons/"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:Yakout.ViewModels"
xmlns:v="clr-namespace:Yakout.Views"
xmlns:local="clr-namespace:Yakout"
mc:Ignorable="d"
Title="MainWindow" Height="700" Width="1100" Background="Transparent" AllowsTransparency="True" WindowStartupLocation="CenterScreen" WindowStyle="None" ResizeMode="NoResize" >
<Window.DataContext>
<vm:NavigationVM></vm:NavigationVM>
</Window.DataContext>
<Border BorderThickness="2" BorderBrush="BlueViolet" Background="White">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="3*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="5*"/>
</Grid.RowDefinitions>
<Button Style="{StaticResource btnCircle}" Grid.Column="1" Click="Button_Click">
<StackPanel>
<fa:ImageAwesome Icon="Close" Grid.Column="1" Style="{StaticResource close}"/>
</StackPanel >
</Button>
<Border Grid.Row="1" Background="BlueViolet" >
<StackPanel >
<Button Style="{StaticResource btnMainMenu}" Name="btnPOS"
Command="{Binding NavigatePosCommand}">
<StackPanel Style="{StaticResource stack}" Orientation="Horizontal">
<fa:ImageAwesome Icon="ShoppingCart" Style="{StaticResource faMainMenu}" Margin="40 0 0 0"/>
<TextBlock Text="Point Of Sale" Style="{StaticResource tbMainMenu}" Margin="30 10 0 0"/>
</StackPanel>
</Button>
<Button Style="{StaticResource btnMainMenu}" Name="btnSetUp" Command="{Binding NavigateUsersCommand}">
<StackPanel Style="{StaticResource stack}" Orientation="Horizontal" >
<fa:ImageAwesome Icon="Key" Style="{StaticResource faMainMenu}"/>
<TextBlock Text="Set Up" Style="{StaticResource tbMainMenu}"/>
</StackPanel>
</Button>
<Button Style="{StaticResource btnMainMenu}" Name="btnReports"
Command="{Binding NavigateUsersSelectCommand}">
<StackPanel Style="{StaticResource stack}" Orientation="Horizontal">
<fa:ImageAwesome Icon="PencilSquare" Style="{StaticResource faMainMenu}"/>
<TextBlock Text="Reports" Style="{StaticResource tbMainMenu}"/>
</StackPanel>
</Button>
<Button Style="{StaticResource btnMainMenu}" Name="btnOptions"
Command="{Binding NavigateMainBackGroundCommand}" >
<StackPanel Style="{StaticResource stack}" Orientation="Horizontal">
<fa:ImageAwesome Icon="HandPaperOutline" Style="{StaticResource faMainMenu}"/>
<TextBlock Text="Options" Style="{StaticResource tbMainMenu}"/>
</StackPanel>
</Button>
<Button Name="btnLogOut" Style="{StaticResource btnMainMenu}" Margin="5 212 5 0" Click="btnLogOut_Click">
<StackPanel Style="{StaticResource stack}" Orientation="Horizontal">
<fa:ImageAwesome Icon="CircleOutlineNotch" Style="{StaticResource faMainMenu}"/>
<TextBlock Text="Log Out" Style="{StaticResource tbMainMenu}"/>
</StackPanel>
</Button>
</StackPanel>
</Border>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Source="/image/R.png"/>
<StackPanel Orientation="Vertical" Grid.Column="1">
<TextBlock Text="Yakout POS" Margin="5 10 5 5" FontSize="25" FontWeight="Bold" HorizontalAlignment="Center"/>
<TextBlock Text="1.0.0.1" FontSize="15" FontWeight="Bold" HorizontalAlignment="Center"/>
<TextBlock Text="Yakout Company" FontSize="15" Foreground="DodgerBlue" FontWeight="Bold" HorizontalAlignment="Center" TextDecorations="Underline"/>
</StackPanel>
</Grid>
<Border Grid.Column="1" Background="BlueViolet">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Canvas>
<Label x:Name="lbl" FontSize="15" Foreground="White" Canvas.Top="10" Canvas.Right="20" Content="{Binding MyTimer}"/>
<TextBlock Text="Point Of Sale" Canvas.Left="250" FontSize="30" Foreground="White" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0 25 0 0"/>
<Ellipse Width="40" Height="40" Fill="DarkViolet" Canvas.Left="150" Canvas.Top="20" StrokeThickness="10"/>
<Ellipse Width="40" Height="40" Fill="DarkViolet" Canvas.Right="230" Canvas.Top="20" StrokeThickness="10"/>
</Canvas>
</Grid>
</Border>
<Rectangle Stroke="BlueViolet" StrokeThickness="3" Grid.Column="0" Grid.Row="0"/>
<ContentControl Content="{Binding CurrentViewModel}" Grid.Row="1" Grid.Column="1" >
</ContentControl>
<!--CurrentView-->
</Grid>
</Border>
the code of the navigated ViewModel , its name UsersVM
the NavigateUsersSelectCommand navigate to new View
and NavigateMainBackGroundCommand navigate back to MainBackGroundView
both commands not working
class UsersVM : Utilities.ViewModelBase
{
public ICommand NavigateUsersSelectCommand { get; }
public ICommand NavigateMainBackGroundCommand { get; }
public UsersVM(NavigationStore navigationStore,SelectedUserStore selectedUserStore)
{
_navigationStore = navigationStore;
NavigateMainBackGroundCommand = new NavigateCommand<MainBackGroundVM>(new NavigationService<MainBackGroundVM>(navigationStore, () => new MainBackGroundVM()));
NavigateUsersSelectCommand = new NavigateCommand<UserSelectVM>(new NavigationService<UserSelectVM>(navigationStore, () => new UserSelectVM(_navigationStore)));
}
}
the xaml code for the usersView
<UserControl x:Class="Yakout.Views.Users"
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:fa="http://schemas.fontawesome.io/icons/"
xmlns:local="clr-namespace:Yakout.Views"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800" Style="{StaticResource user}"
>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.NavigateUsersSelectCommand}">-->
<StackPanel Orientation="Horizontal">
<Button x:Name="select" Style="{StaticResource btnUsers}"
Command="{Binding NavigateUsersSelectCommand}">
<StackPanel>
<fa:ImageAwesome Icon="HandPointerOutline" Style="{StaticResource fa}"/>
<TextBlock Text="Select" Style="{StaticResource btnText}"/>
</StackPanel>
</Button>
<Button x:Name="new" Style="{StaticResource btnUsers}" Click="new_Click">
<StackPanel>
<fa:ImageAwesome Icon="NewspaperOutline" Style="{StaticResource fa}"/>
<TextBlock Text="New" Style="{StaticResource btnText}"/>
</StackPanel>
</Button>
<Button x:Name="save" Style="{StaticResource btnUsers}" Click="save_Click">
<StackPanel>
<fa:ImageAwesome Icon="Save" Style="{StaticResource fa}"/>
<TextBlock Text="Save" Style="{StaticResource btnText}"/>
</StackPanel>
</Button>
<Button x:Name="first" Style="{StaticResource btnUsers}" Click="first_Click">
<StackPanel>
<fa:ImageAwesome Icon="FastBackward" Style="{StaticResource fa}"/>
<TextBlock Text="First" Style="{StaticResource btnText}"/>
</StackPanel>
</Button>
<Button x:Name="back" Style="{StaticResource btnUsers}" Click="back_Click">
<StackPanel>
<fa:ImageAwesome Icon="Backward" Style="{StaticResource fa}"/>
<TextBlock Text="Back" Style="{StaticResource btnText}"/>
</StackPanel>
</Button>
<Button x:Name="next" Style="{StaticResource btnUsers}" Click="next_Click">
<StackPanel>
<fa:ImageAwesome Icon="Forward" Style="{StaticResource fa}"/>
<TextBlock Text="Next" Style="{StaticResource btnText}"/>
</StackPanel>
</Button>
<Button x:Name="last" Style="{StaticResource btnUsers}" Click="last_Click">
<StackPanel>
<fa:ImageAwesome Icon="FastForward" Style="{StaticResource fa}"/>
<TextBlock Text="Last" Style="{StaticResource btnText}"/>
</StackPanel>
</Button>
</StackPanel>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<StackPanel>
<Label Content="User Name" Style="{StaticResource labelUsers}"/>
<Label Content="Password" Style="{StaticResource labelUsers}"/>
<Label Content="Full Name" Style="{StaticResource labelUsers}"/>
<Label Content="Job Des" Style="{StaticResource labelUsers}"/>
<Label Content="Email" Style="{StaticResource labelUsers}"/>
<Label Content="Phone" Style="{StaticResource labelUsers}"/>
</StackPanel>
<StackPanel Grid.Column="1">
<TextBox Name="tx1" Style="{StaticResource box}" Text="{Binding Path=UserName,Mode=OneWay}"/>
<TextBox Name="tx2" Style="{StaticResource box}" Text="{Binding Path=Password,Mode=OneWay}"/>
<TextBox Name="tx3" Style="{StaticResource box}" Text="{Binding Path=FullName,Mode=OneWay }"/>
<TextBox Name="tx4" Style="{StaticResource box}" Text="{Binding Path=JobDes,Mode=OneWay}"/>
<TextBox Name="tx5" Style="{StaticResource box}" Text="{Binding Path=Email,Mode=OneWay }"/>
<TextBox Name="tx6" Style="{StaticResource box}" Text="{Binding Path=Phone,Mode=OneWay }"/>
</StackPanel>
<Canvas Grid.Column="2">
<Button x:Name="btnBack" Style="{StaticResource btnPages}"
Canvas.Right="5" Canvas.Bottom="5"
Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.NavigateMainBackGroundCommand}">
<StackPanel>
<fa:ImageAwesome Icon="Backward" Style="{StaticResource faPagesBack}"/>
<TextBlock Text="Back" Style="{StaticResource tbPagesBack}"/>
</StackPanel>
</Button>
</Canvas>
</Grid>
</Grid>
the xaml code for the mainBackGroundView
<UserControl x:Class="Yakout.Views.MainBackGround"
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:Yakout.Views"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Image Source="/image/kkk.jpg" Stretch="Fill"/>
</Grid>
data template for the app
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:Yakout.ViewModels"
xmlns:view="clr-namespace:Yakout.Views">
<DataTemplate DataType="{x:Type vm:OptionsVM}">
<view:Options/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:MainBackGroundVM}">
<view:MainBackGround/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:SetUpVM}">
<view:SetUP/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:PosVM}">
<view:Pos/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:ReportsVM}">
<view:Reports/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:UsersVM}">
<view:Users/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:UserSelectVM}">
<view:UserSelect/>
</DataTemplate>
code for the app.xml
<Application x:Class="Yakout.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Yakout"
>
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Styles/StylesMainWindow.xaml" />
<ResourceDictionary Source="Styles/StylesMain.xaml" />
<ResourceDictionary Source="Styles/StylesUcOptions.xaml" />
<ResourceDictionary Source="/Utilities/DataTemplate.xaml"/>
<ResourceDictionary Source="/Styles/StylesUsers.xaml"/>
<ResourceDictionary Source="/Styles/StylesUserSelect.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
NavigationService
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yakout.Stores;
namespace Yakout.Utilities
{
class NavigationService<TViewModel>
where TViewModel:ViewModelBase
{
private readonly NavigationStore _navigationStore;
private readonly Func<TViewModel> _CreateViewModel;
public NavigationService(NavigationStore navigationStore,Func<TViewModel>CreateViewModel)
{
_navigationStore = navigationStore;
_CreateViewModel = CreateViewModel;
}
public void Navigate()
{
_navigationStore.CurrentViewModel = _CreateViewModel();
}
}
}
ParameterNavigationService
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yakout.Stores;
namespace Yakout.Utilities
{
class ParameterNavigationService<TParameter, TViewModel>
where TViewModel:ViewModelBase
{
private readonly NavigationStore _navigationStore;
private readonly Func<TParameter,TViewModel> _createVM;
public ParameterNavigationService(NavigationStore navigationStore, Func<TParameter, TViewModel> createVM)
{
_navigationStore = navigationStore;
_createVM= createVM;
}
public void Navigate(TParameter parameter)
{
_navigationStore.CurrentViewModel = _createVM(parameter);
}
}
}
NavigateMainBackGroundCommand
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Navigation;
using Yakout.Stores;
using Yakout.Utilities;
using Yakout.ViewModels;
namespace Yakout.Commands
{
class NavigateMainBackGroundCommand : Utilities.CommandBase
{
/// <summary>
/// حاليا مفيش احتياج لاوامر دي
/// </summary>
private readonly NavigationService<MainBackGroundVM> _navigationService;
private readonly MainBackGroundVM _mainBackGroundVM;
public NavigateMainBackGroundCommand(MainBackGroundVM mainBackGroundVM, NavigationService<MainBackGroundVM> navigationService)
{
_navigationService = navigationService;
_mainBackGroundVM = mainBackGroundVM;
}
public override void Execute(object parameter)
{
_navigationService.Navigate();
}
}
}
NavigateUsersCommand
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Yakout.Stores;
using Yakout.ViewModels;
namespace Yakout.Commands
{
class NavigateUsersCommand : Utilities.CommandBase
{
private readonly NavigationStore _navigationStore;
private readonly SelectedUserStore _selectedUserStore;
public NavigateUsersCommand(NavigationStore navigationStore, SelectedUserStore selectedUserStore)
{
_navigationStore = navigationStore;
_selectedUserStore = selectedUserStore;
}
public override void Execute(object parameter)
{
_navigationStore.CurrentViewModel = new UsersVM(_navigationStore,_selectedUserStore);
}
}
}
this is my code on GitHub
github.com/amryakout1990/Yakout.git
i want solution for my problem
Looking at one of these commands you have in your view:
<Button x:Name="select" Style="{StaticResource btnUsers}"
Command="{Binding NavigateUsersSelectCommand}">
In the viewmodel:
NavigateUsersSelectCommand = new NavigateCommand<UserSelectVM>(new NavigationService<UserSelectVM>(navigationStore, () => new UserSelectVM(_navigationStore)));
That expects a command parameter of UserSelectVM type.
You are not passing that because you define no commandparameter in xaml.
Does it even bind? I would have thought there'd be an error in your xaml errors window in vs2022 or the output window.
I guess this is the selected user you want so you could make the commandparameter selecteditem or you could bind selecteditem and reference it in the aonymous method you have there.
But that is why that command does not work.
I didn't look at other commands because there's quite a lot of code to look through. I suggest you fix that one first and see if you have a similar issue repeated.

WPF Prism EventAggregator subscriber does not get the published event

I am trying to implement Prism EventAggregator in building an App using Prism.
My design is as below:
Publisher VM class
class MainViewModel : INotifyPropertyChanged
{
private LADataService lADataService;
LADataService sa = new LADataService();
public List<LAInfo> LADetails
{
get
{
return this._laDetails;
}
set
{
if (this._laDetails != value)
{
this._laDetails = value;
this.NotifyPropertyChanged("LADetails");
}
}
}
public LAInfo SelectedLA
{
get
{
return _selectedla;
}
set
{
if (_selectedla != value)
{
_selectedla = value;
NotifyPropertyChanged("SelectedLA");
//NavigationParameters navParameter = new NavigationParameters();
//navParameter.Add("SelectedLA", SelectedLA);
// Publish event.
iEventAggregator
.GetEvent<PubSubEvent<LAInfo>>()
.Publish(this.SelectedLA);
}
}
}
Subscriber VM
class PopUpFormViewModel : INotifyPropertyChanged, INavigationAware
{
private LAInfo _lainfo;
public LAInfo LAInfo
{
get
{
return this._lainfo;
}
set
{
if (this._lainfo != value)
{
this._lainfo = value;
this.NotifyPropertyChanged("LAInfo");
}
}
}
public PopUpFormViewModel(IEventAggregator iEventAggregator)
{
this.iEventAggregator = iEventAggregator;
this
.iEventAggregator
.GetEvent<PubSubEvent<LAInfo>>()
.Subscribe((details) =>
{
this.LAInfo = details;
});
}
Publisher xaml
<UserControl x:Class="USBReaderFinal.Views.Main"
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:USBReaderFinal.Views"
xmlns:design="clr-namespace:USBReaderFinal.Designer"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="71*"/>
<RowDefinition Height="154*"/>
</Grid.RowDefinitions>
<Grid Margin="10,0,0,0" Grid.RowSpan="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="108*"/>
<ColumnDefinition Width="287*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="0*"/>
<RowDefinition Height="31*"/>
<RowDefinition Height="5*"/>
<RowDefinition Height="0*"/>
<RowDefinition Height="63*"/>
<RowDefinition Height="351*"/>
</Grid.RowDefinitions>
<!--<ContentControl Content="{Binding SelectedViewModel}" Grid.RowSpan="6" Grid.ColumnSpan="2"/>-->
<materialDesign:Card
materialDesign:ShadowAssist.ShadowDepth="Depth3"
materialDesign:ShadowAssist.ShadowEdges="Bottom"
Padding="32"
Content="LAs with Max Date.Right click the list content to Select/Add/View graphs" FontSize="16" FontStyle="Italic" FontWeight="Bold" OpacityMask="{DynamicResource {x:Static SystemColors.InfoBrushKey}}" Foreground="{DynamicResource {x:Static SystemColors.ControlDarkBrushKey}}" Grid.RowSpan="6" Grid.ColumnSpan="2" >
<materialDesign:Card.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="#FF00FF91" Offset="1"/>
</LinearGradientBrush>
</materialDesign:Card.Background>
</materialDesign:Card>
<Frame
x:Name="NavigationFrame"
NavigationUIVisibility="Hidden"
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Left"
ScrollViewer.CanContentScroll="True"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.VerticalScrollBarVisibility="Auto"
Margin="6" Grid.RowSpan="6" Grid.ColumnSpan="2"
/>
<ListView Name="LA" ItemsSource="{Binding LADetails}" SelectedItem="{Binding SelectedLA}" HorizontalAlignment="Left" Height="215" VerticalAlignment="Top" Width="649" Margin="94,36,0,0" Foreground="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" Grid.Row="3" Grid.RowSpan="3" Grid.ColumnSpan="2" >
<ListView.ContextMenu>
<ContextMenu>
<MenuItem Name="Add" Header="Add New LA" />
<MenuItem Name="Update" Header="Update LA" />
<MenuItem Name="Delete" Header="Delete Selected LA" />
<MenuItem Name="Graph" Header="Display Graph" />
</ContextMenu>
</ListView.ContextMenu>
<ListView.ItemTemplate>
<DataTemplate>
<WrapPanel>
<TextBlock Text="LAName: " />
<TextBlock Text="{Binding LAname}" FontWeight="Bold" />
<TextBlock Text=", " />
<TextBlock Text=" LAMAke: " />
<TextBlock Text="{Binding LAMAke}" FontWeight="Bold" />
<TextBlock Text=" Phase: " />
<TextBlock Text="{Binding Phase}" FontWeight="Bold" />
<TextBlock Text=" Board: " />
<TextBlock Text="{Binding Board}" FontWeight="Bold" />
<TextBlock Text=" FF: " />
<TextBlock Text="{Binding Path=ld.FF}" FontWeight="Bold" />
<TextBlock Text=" CTHD: " />
<TextBlock Text="{Binding Path=ld.Cthd}" FontWeight="Bold" />
<TextBlock Text=" TTHD: " />
<TextBlock Text="{Binding Path=ld.TThd}" FontWeight="Bold" />
<TextBlock Text=" Temp: " />
<TextBlock Text="{Binding Path=ld.Temp}" FontWeight="Bold" />
<TextBlock Text=" Comptemll: " />
<TextBlock Text="{Binding Path=ld.Comptell}" FontWeight="Bold" />
<TextBlock Text=" Date: " />
<TextBlock Text="{Binding Path=ld.Max_date}" FontWeight="Bold" />
</WrapPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Grid>
</UserControl>
Subscriber xaml
<UserControl x:Class="USBReaderFinal.Views.PopUpFormUSB"
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:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
xmlns:design="clr-namespace:USBReaderFinal.Designer"
mc:Ignorable="d"
d:DesignHeight="450" Width="800">
<Grid >
<StackPanel Margin="108,0,0,0">
<Label Content="LAName" Width="71" HorizontalAlignment="Left" VerticalAlignment="Center" Foreground="DarkOrange" FontSize="14"/>
<Label Content="LAMake" Width="71" HorizontalAlignment="Left" VerticalAlignment="Center" Foreground="DarkOrange" FontSize="14"/>
<Label Content="CTHD" Width="71" HorizontalAlignment="Left" VerticalAlignment="Center" Foreground="DarkOrange" FontSize="14"/>
<Label Content="FF" Width="113" HorizontalAlignment="Left" VerticalAlignment="Center" Foreground="DarkOrange" FontSize="14"/>
<Label Content="Temp" Width="113" HorizontalAlignment="Left" VerticalAlignment="Center" Foreground="DarkOrange" FontSize="14"/>
</StackPanel>
<StackPanel Margin="345,0,0,0">
<ContentControl Grid.Row="1" Content="{Binding LAInfo}">
<ContentControl.ContentTemplate>
<DataTemplate>
</DataTemplate>
</ContentControl.ContentTemplate>
</ContentControl>
<TextBox Width="201" HorizontalAlignment="Left" VerticalAlignment="Stretch" Foreground="AliceBlue" Height="30"
Text="{Binding LAName,
Delay=1000,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"
OpacityMask="#FF00A2FF" Background="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}" />
<TextBox Width="201" HorizontalAlignment="Left" VerticalAlignment="Center" Foreground="AliceBlue" Height="30"
Text="{Binding LAMake,
Delay=1000,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" Background="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}" />
<TextBox Width="201" HorizontalAlignment="Left" VerticalAlignment="Center" Foreground="AliceBlue" Height="25" Text="{Binding CTHD,
Delay=1000,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" Background="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}"/>
<TextBox Width="201" HorizontalAlignment="Left" VerticalAlignment="Center" Foreground="AliceBlue" Height="23" Text="{Binding FF,
Delay=1000,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" Background="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}"/>
<TextBox Width="201" HorizontalAlignment="Left" VerticalAlignment="Center" Height="27" Text="{Binding Temp, Delay=1000, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Background="{DynamicResource {x:Static SystemColors.ActiveBorderBrushKey}}"/>
</StackPanel>
</Grid>
</UserControl>
Basically when I select an item from the listview of main, the selected item
should pass as an paramter to Popup view.
When I debugged the eventaggregator code, in the Subscriber VM I get null passed for the
LAInfo object in below code
public PopUpFormViewModel(IEventAggregator iEventAggregator)
{
this.iEventAggregator = iEventAggregator;
this
.iEventAggregator
.GetEvent<PubSubEvent>()
.Subscribe((details) =>
{
this.LAInfo = details;
});
}
Bootstrapper (In case required)
class BootStrapper : AutofacBootstrapper
{
protected override DependencyObject CreateShell()
{
return Container.Resolve<MainWindow>();
}
protected override void InitializeShell()
{
Application.Current.MainWindow.Show();
}
protected override void ConfigureContainerBuilder(ContainerBuilder builder)
{
base.ConfigureContainerBuilder(builder);
//builder.RegisterType<MainViewModel>().SingleInstance();
// builder.RegisterType<DataPassOnService>().As<ILAInfos>().SingleInstance();
builder.RegisterType<LADataService>().SingleInstance();
builder.RegisterType<USBDataService>().SingleInstance();
//builder.RegisterType<DataPassOnService>().SingleInstance();
builder.RegisterTypeForNavigation<Main>("Main");
builder.RegisterTypeForNavigation<LeftMenu>("LeftMenu");
builder.RegisterTypeForNavigation<PopUpFormUSB>("PopUpFormUSB");
builder.RegisterTypeForNavigation<USBListAccess>("USBListAccess");
// builder.RegisterType<USBListAccessViewModel>()
// //.As<IUSBService>()
// .UsingConstructor(typeof(USBDataService));
// builder.RegisterType<PopUpFormViewModel>().InstancePerRequest();
////.As<ILAInfos>()
//.UsingConstructor(typeof(DataPassOnService));
}
What is happening here and why I am seeing null here, this is the object which I am planning to
pass to the Subscriber xaml, which will not reach as the code will exception out due to null pointer exception.
Do I need to pass on the above selected item to NavigateTo method which will navigate to the second view with the selected parameter? If so, how do I go about doing it? I am kind of stuck. Any sort of direction is much appreciated. Thanks in advance.

Passing Data to Respective Textboxes from DataGrid after clicking particular Row in Datagrid

I am to new WPF. I need to pass the data from DataGrid to textboxes. I searched many sites but all were explaining by considering DataGridview (which has event called CellContentClick) but that event is not there in DataGrid (I am using vs2010).
I have defined textboxes in Usercontrol and used that in mainwindow for 4 Tabs.
1.MainWindow.xaml code
<Grid>
<TabControl x:Name="TabControl1">
<TabItem Header="View Details" x:Name="Tab1">
<StackPanel>
<uc:CustomerUC x:Name="ViewData"></uc:CustomerUC>
<Button Content="UpdateDataGrid" Height="25" Width="180" Name="UpGridBtn" Click="UpGridBtn_Click" Margin="15" Visibility="{Binding UpGridVisibility}"/>
<DataGrid AutoGenerateColumns="False" CanUserAddRows="False" ItemsSource="{Binding CustomersData}" x:Name="DGdata" Margin="0 20 0 10">
<DataGrid.Columns>
<DataGridTextColumn Header="CustomerID" Binding="{Binding Path=CustoID}" IsReadOnly="True" />
<DataGridTextColumn Header="CustomerName" Binding="{Binding Path=CustoName}" IsReadOnly="True"/>
<DataGridTextColumn Header="CustomerAge" Binding="{Binding Path=CustoAge}" IsReadOnly="True"/>
<DataGridTextColumn Header="CustomerAddress" Binding="{Binding Path=CustoAddress}" IsReadOnly="True"/>
<DataGridTextColumn Header="CustomerEmail" Binding="{Binding Path=CustoEmail}" IsReadOnly="True" />
<DataGridTextColumn Header="CustomerMobile" Binding="{Binding Path=CustoMobile}" IsReadOnly="True"/>
<DataGridTextColumn Header="CustomerUserName" Binding="{Binding Path=CustoUname}" IsReadOnly="True"/>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</TabItem>
<TabItem Header="Add Details" x:Name="Tab2">
<uc:CustomerUC x:Name="AddData"></uc:CustomerUC>
</TabItem>
<TabItem Header="Update Details" x:Name="Tab3">
<uc:CustomerUC x:Name="UpdateData"></uc:CustomerUC>
</TabItem>
<TabItem Header="Delete Details" x:Name="Tab4">
<uc:CustomerUC x:Name="DeleteData"></uc:CustomerUC>
</TabItem>
</TabControl>
</Grid>
2.Usercontrol code
<StackPanel >
<StackPanel Orientation="Horizontal" Visibility="{Binding CustIDVisibility}" >
<Button x:Name="CustID" Content="Customer ID" Width="100" Margin="82 0 0 0" Click="CustID_Click" />
<ComboBox Height="25" Width="180" x:Name="ComboID" SelectionChanged="ComboID_SelectionChanged" />
</StackPanel>
<StackPanel Orientation="Horizontal" Visibility="{Binding CustomerIDVisibility}" >
<Label x:Name="CustoID" Content="Customer ID" Width="100" Margin="82 0 0 0"/>
<TextBox x:Name="BoxID" Margin="2" Width="180" Text="{Binding ElementName=DGdata, Path=SelectedItem.CustoID}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" >
<Label x:Name="CustName" Content="Customer Name" Width="100" Margin="82 0 0 0"/>
<TextBox x:Name="BoxName" Margin="2" Width="180" Text="{Binding ElementName=DGdata, Path=SelectedItem.CustoName}"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label x:Name="CustAge" Content=" Age" Width="100" Margin="82 0 0 0"/>
<TextBox x:Name="BoxAge" Margin="2" Width="180" Text="{Binding ElementName=DGdata, Path=SelectedItem.CustoAge}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" >
<Label x:Name="CustAddress" Content="Address" Width="100" Margin="82 0 0 0"/>
<TextBox x:Name="BoxAddress" Margin="2" Width="180" Text="{Binding ElementName=DGdata, Path=SelectedItem.CustoAddress}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" >
<Label x:Name="CustEmail" Content="Email ID" Width="100" Margin="82 0 0 0"/>
<TextBox x:Name="BoxEmail" Margin="2" Width="180" Text="{Binding ElementName=DGdata, Path=SelectedItem.CustoEmail}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" >
<Label x:Name="CustMobile" Content="Mobile No." Width="100" Margin="82 0 0 0" />
<TextBox x:Name="BoxMobile" Margin="2" Width="180" Text="{Binding ElementName=DGdata, Path=SelectedItem.CustoMobile}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" >
<Label x:Name="CustUname" Content="User Name" Width="100" Margin="82 0 0 0"/>
<TextBox x:Name="BoxUname" Margin="2" Width="180" Text="{Binding ElementName=DGdata, Path=SelectedItem.CustoUname}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Visibility="{Binding pwdVisibility}" >
<Label x:Name="CustPWD" Content="Password" Width="100" Margin="82 0 0 0"/>
<TextBox x:Name="BoxPWD" Margin="2" Width="180" />
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="82 15 0 0" >
<Button x:Name="CancelBtn" Content="Cancel" Width="100" Height="25" Margin="2"/>
<Button x:Name="SaveBtn" Content="Save" Width="100" Height="25" Margin="2" Visibility="{Binding SaveVisibility}" Click="SaveBtn_Click" />
<Button x:Name="UpdateBtn" Content="Update" Width="100" Height="25" Margin="2" Visibility="{Binding UpdateVisibility}" Click="UpdateBtn_Click" />
<Button x:Name="DeleteBtn" Content="Delete" Width="100" Height="25" Margin="2" Visibility="{Binding DeleteVisibility}" Click="DeleteBtn_Click" />
</StackPanel>
</StackPanel>
//
3.Model Code
class CustomerDataModel
{
public int CustoID { get; set; }
public string CustoName { get; set; }
public int CustoAge { get; set; }
public string CustoAddress { get; set; }
public string CustoEmail { get; set; }
public string CustoMobile { get; set; }
public string CustoUname { get; set; }
}
//
View Model Code
public CustoDataPassVM()
{
FillGrid();
}
public void FillGrid()
{
PurchaseNowEntities Entity = new PurchaseNowEntities();
var datalist = from r in Entity.tblCustomerDetails select r;
if (CustomersData == null)
CustomersData = new ObservableCollection<CustomerDataModel>();
foreach (var r in datalist)
{
CustomersData.Add(new CustomerDataModel
{
CustoID = r.CustomerID,
CustoName = r.CustomerName,
CustoAge = r.CustomerAge,
CustoAddress = r.CustomerAddress,
CustoEmail = r.CustomerEmailID,
CustoMobile = r.CustomerMobile,
CustoUname = r.CustomerUname
});
}
}
5.With help of datacontext i am able to get data in datagrid
public MainWindow()
{
InitializeComponent();
CO = new CustoDataPassVM();
DGdata.DataContext = CO;
}
Output screenshots pics
If i use both textbox and datagrid in SAME WINDOW i will be able to get data on textboxes with help of
Text="{Binding ElementName=DGdata, Path=SelectedItem.CustoID}
But when i separate the datagrid in mainwindow and textboxes in Usercontrol. I think it is not finding datagrid of ElementName= DGdata in usercontrol window, so it is not binding in texboxes i think.
So how to pass data of datagrid(selected row) from mainwindow to usercontrol textboxes
And I tried with SelectionChanged handler, in this i am to get each cell value, but it is not bind to textboxes( ex: BoxName.text is getting assigned but not in textbox of it..
SelectionChanged handler code:
public void DGdata_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
CustomerUC bindnow = new CustomerUC();
CustomerDataModel row = (CustomerDataModel)DGdata.SelectedItem;
bindnow.BoxName.Text = row.CustoName;
}

Delete a subitem in a tree view with heirarchical data template

Please find below my XAML,
<loc:MultiSelectTreeView Height="295" ScrollViewer.VerticalScrollBarVisibility="Visible" BorderThickness="1" Background="WhiteSmoke" x:Name="GridListEmulation" Grid.Row="2" BorderBrush="Gray" ItemsSource="{Binding EmulationCollection,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" Margin="0,2,0,-2"
ItemContainerStyle="{StaticResource MultiSelectTreeViewItemStyle}" SelectedItemChanged="GridListEmulation_SelectedItemChanged">
<TreeView.ItemTemplate >
<HierarchicalDataTemplate ItemsSource="{Binding Items,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" >
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="Stream" Width="60"/>
<ColumnDefinition SharedSizeGroup="Port" Width="55"/>
<ColumnDefinition SharedSizeGroup="Device Name" Width="100"/>
<ColumnDefinition SharedSizeGroup="Count" Width="50"/>
<ColumnDefinition SharedSizeGroup="FromMAC" Width="120"/>
<ColumnDefinition SharedSizeGroup="State" Width="60"/>
<ColumnDefinition SharedSizeGroup="MACAddress" Width="120"/>
<ColumnDefinition SharedSizeGroup="EmulationIPv4Address" Width="100"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding StreamId}" Style="{StaticResource TextBlockStyle}"/>
<TextBlock Grid.Column="1" Text="{Binding Port}" Style="{StaticResource TextBlockStyle}"/>
<TextBlock Grid.Column="2" Text="{Binding EmulationDeviceName}" Style="{StaticResource TextBlockStyle}"/>
<TextBlock Grid.Column="3" Text="{Binding SessionCount}" Style="{StaticResource TextBlockStyle}"/>
<TextBlock Grid.Column="4" Text="{Binding SourceMAC}" Style="{StaticResource TextBlockStyle}"/>
<TextBlock Grid.Column="5" Text="{Binding State}" Style="{StaticResource TextBlockStyle}"/>
<TextBlock Grid.Column="6" Text="{Binding SimulatedMAC}" Style="{StaticResource TextBlockStyle}"/>
<TextBlock Grid.Column="7" Text="{Binding EmulationIPv4Address}" Style="{StaticResource TextBlockStyle}"/>
</Grid>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</loc:MultiSelectTreeView>
I am trying to delete a subitem in this multi treeview which is bound to my observable collection as shown below,
tvm.EmulationCollection.RemoveAt(GridListEmulation.Items.IndexOf(subItem));
But i always get the index as -1 for subitem and then gives an exception. Please let me know if any way to get the subitem in the tree view item of the heirarchical data template and delete it? Thanks in advance.
here is a basic example of using a VM to host a tree
public class TreeVM : BindableBase
{
public TreeVM()
{
AddChild = new DelegateCommand(() => Items.Add(new TreeVM() {Parent = this }));
RemoveMe = new DelegateCommand(() => Parent.Items.Remove(this));
}
private string _Text;
public string Text
{
get { return _Text; }
set { SetProperty(ref _Text, value); }
}
private TreeVM _Parent;
public TreeVM Parent
{
get { return _Parent; }
set { SetProperty(ref _Parent, value); }
}
public ObservableCollection<TreeVM> Items { get; } = new ObservableCollection<TreeVM>();
public DelegateCommand AddChild { get; set; }
public DelegateCommand RemoveMe { get; set; }
}
then hosted on this XAML
<StackPanel>
<Button Content="Add" Command="{Binding AddChild}"/>
<TreeView ItemsSource="{Binding Items}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Items}">
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding Text}"/>
<Button Content="Add" Command="{Binding AddChild}"/>
<Button Content="Delete" Command="{Binding RemoveMe}"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</StackPanel>
as you can see the child is responsible for removing itself from the tree, and this works because your VM knows its parent as well as its children

Closing Caliburn Micro View from a UserControl Button?

I have created a UserControl name TitleBar, which is placed in every view.
The TitleBar.xaml contains a Button to close the Window in which it contain.
How can i close a Caliburn Window using that Button.
TitleBar UserControl
<UserControl x:Class="JIMS.Controls.TitleBar"
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">
<Grid Style="{StaticResource TitleBar}">
<Rectangle HorizontalAlignment="Stretch" Height="7" Margin="0,0,-5,0" VerticalAlignment="Top" Fill="{DynamicResource DefaultBrush}"></Rectangle>
<Grid HorizontalAlignment="Left" Margin="-10,-5,0,0" Name="Logo">
<TextBlock Name="txtTitle" Style="{StaticResource Title}">JIMS</TextBlock>
<Ellipse HorizontalAlignment="Right" Margin="0,0,5,0" Width="20" Height="20">
<Ellipse.Fill>
<VisualBrush Stretch="Fill" Visual="{StaticResource appbar_settings_white}" />
</Ellipse.Fill>
</Ellipse>
</Grid>
<Grid HorizontalAlignment="Right">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,5,-4,0">
<Button Name="btnClose" Style="{StaticResource ChromeButtonStyle}" Click="btnClose_Click" IsTabStop="False">
<TextBlock TextWrapping="Wrap" Text="r" FontFamily="Webdings" Foreground="#FF919191" FontSize="13.333" />
</Button>
</StackPanel>
</Grid>
</Grid>
</UserControl>
TitleBar Usage in a View
<UserControl xmlns:my="clr-namespace:JIMS.Controls;assembly=JIMS.Controls" x:Class="JIMS.Views.Stock.UnitView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="Unit">
<Border Style="{StaticResource WindowBorderStyle}">
<StackPanel Orientation="Vertical">
<my:TitleBar Title="unit creation"/>
<StackPanel Visibility="{Binding ControlVisiblity}" Orientation="Horizontal" Margin="0,5,0,5">
<StackPanel Orientation="Vertical" Margin="10,0,0,0">
<Label>Short Name :</Label>
<Label>Unit Name :</Label>
</StackPanel>
<StackPanel Orientation="Vertical" Width="200" Margin="0,0,10,0">
<TextBox Name="txtShortName" Text="{Binding Path=UnitShort}"></TextBox>
<TextBox Name="txtUnitName" Text="{Binding Path=UnitName}"></TextBox>
</StackPanel>
</StackPanel>
<Expander Style="{StaticResource DisplayExpander}" IsExpanded="{Binding IsDisplayExpanded}" Header="display units">
<StackPanel Orientation="Horizontal" Margin="0,5,0,5" Visibility="{Binding DisplayVisiblity}">
<DataGrid AutoGenerateColumns="True" Height="200" MinWidth="300" ItemsSource="{Binding Display}"></DataGrid>
</StackPanel>
</Expander>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Button Name="SaveUnit" Style="{StaticResource MetroButton}">Save</Button>
</StackPanel>
</StackPanel>
</Border>
</UserControl>
In your TitleBar control define a RoutedEvent like this
public event RoutedEventHandler CloseClick
{
add { AddHandler(CloseClickEvent, value); }
remove { RemoveHandler(CloseClickEvent, value); }
}
public static readonly RoutedEvent CloseClickEvent = EventManager.RegisterRoutedEvent(
"CloseClick", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(TitleBar));
void RaiseCloseClickEvent()
{
var newEventArgs = new RoutedEventArgs(TitleBar.CloseClickEvent);
RaiseEvent(newEventArgs);
}
private void btnClose_Click(object sender, RoutedEventArgs e)
{
RaiseCloseClickEvent();
}
And attach the btnClose_Click event handler to the btnClose control in your TitleBar
Now, when you use your TitleBar add an action like this
<my:TitleBar Title="This is the title">
<i:Interaction.Triggers>
<i:EventTrigger EventName="CloseClick">
<cal:ActionMessage MethodName="Close"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</my:TitleBar>
This will call the method Close on your viewmodel when the the CloseClickEvent is raised on the TitleBar.
For closing the window, you could derive your viewmodel from Screen and add the following snippet
public void Close()
{
TryClose();
}

Resources