WPF Designer Error (System.NullReferenceException) loading MahApps.Metro.Controls - wpf

I'm getting an unhandled exception when loading the designer (VS2010)
These are the details.
System.NullReferenceException
Object reference not set to an instance of an object.
at MahApps.Metro.Controls.TextboxHelper.TextBoxLoaded(Object sender, RoutedEventArgs e)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
at System.Windows.BroadcastEventHelper.BroadcastEvent(DependencyObject root, RoutedEvent routedEvent)
at System.Windows.BroadcastEventHelper.BroadcastLoadedEvent(Object root)
at MS.Internal.LoadedOrUnloadedOperation.DoWork()
at System.Windows.Media.MediaContext.FireLoadedPendingCallbacks()
at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
I have tried
--commenting out all text boxes
--commenting out all code in my viewmodel constructor
--commenting out the MainWindowVieWModel creation in the MainWindow constructor...
I'm baffled..
Code...
public partial class MainWindow : MetroWindow
{
public MainWindowViewModel ViewModel { get; protected set; }
public MainWindow()
{
ViewModel = new MainWindowViewModel(new AppModel());
InitializeComponent();
}
public class AppModel : ReactiveValidatedObject
{
public ReactiveCollection<SheetModel> CompletedSheets { get; protected set; }
public void RefreshData()
{
List<SheetModel> sheets = DataLayer.LoadData();
CompletedSheets = new ReactiveCollection<SheetModel>();
foreach (var sheetModel in sheets)
{
CompletedSheets.Add(sheetModel);
}
}
public AppModel()
{
CompletedSheets = new ReactiveCollection<SheetModel>();
}
Constructor for main window view model is empty, so shouldn't be any issues there.
MainWindowXaml...
<Controls:MetroWindow
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="TimeSheet.MainWindow"
Title="MainWindow"
x:Name="Window"
Height="270"
MinWidth="490"
Width="600"
xmlns:local="clr-namespace:TimeSheet"
ShowTitleBar="False" WindowStartupLocation="CenterScreen"
DataContext="{Binding ViewModel, ElementName=Window}">
<Controls:MetroWindow.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colours.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
</ResourceDictionary.MergedDictionaries>
<DataTemplate x:Key="CompletedBlockTile">
<StackPanel Orientation="Vertical" Margin="10,0,0,0">
<TextBlock Text="{Binding Date}" FontWeight="Bold" FontFamily="Segoe UI" />
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="TaskTemplate">
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition MinWidth="80px"/>
<ColumnDefinition Width="50px" />
<ColumnDefinition Width="40px"/>
<ColumnDefinition Width="40px"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Description}" Height="25.3" Margin="0" HorizontalAlignment="Stretch"/>
<TextBlock Grid.Column="1" Text="{Binding Duration}" Margin="0,0,0,0" Height="25.3" Width="45.625"/>
<Button Grid.Column="2" Content=">>" HorizontalAlignment="Right" Width="38" Command="{Binding ReStartCommand}"/>
<Button Grid.Column="3" Content="STOP" VerticalAlignment="Top" Margin="0,0,0,0" Command="{Binding StopCommand}" HorizontalAlignment="Right" Width="35"/>
</Grid>
</DataTemplate>
<BitmapImage x:Key="SearchImage" UriSource="Images/blue-37.png" />
</ResourceDictionary>
</Controls:MetroWindow.Resources>
<Controls:MetroWindow.WindowCommands>
<Controls:WindowCommands>
<Button x:Name="thisButton">
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Horizontal">
<Label Margin="0,0,55,0" Content="09:00"/>
<Label Margin="0,0,5,0" Content="Friday 20th July 2012"/>
<TextBox Controls:TextboxHelper.Watermark="search"
Controls:TextboxHelper.ClearTextButton="True"
VerticalAlignment="Top"
HorizontalAlignment="Left"
Width="154.002" />
<Button Style="{DynamicResource ChromelessButtonStyle}" Click="Button_Click">
<Image Source="{StaticResource SearchImage}" Width="20"/>
</Button>
</StackPanel>
</StackPanel>
</Button>
</Controls:WindowCommands>
</Controls:MetroWindow.WindowCommands>
<DockPanel Margin="0,0,0,0" >
<DockPanel DockPanel.Dock="Left" Margin="0,0,0,0" Width="176.625" >
<ListBox Background="Transparent"
BorderBrush="Transparent"
Margin="0,30,0,0"
ItemsSource="{Binding CompletedSheets}"
ItemTemplate="{DynamicResource CompletedBlockTile}"
SelectedItem="{Binding SelectedTimeSheet}"/>
</DockPanel>
<DockPanel DockPanel.Dock="Right" >
<Grid Margin="0,30,0,0" VerticalAlignment="Top" DockPanel.Dock="Top">
<Grid Margin="0,0,14,0.805">
<local:TextBoxChangeExt
MinWidth="200"
Controls:TextboxHelper.Watermark="Task Name"
Controls:TextboxHelper.ClearTextButton="True"
d:LayoutOverrides="Height"
Margin="8,0,70,0"
Background="{x:Null}"
Text="{Binding NewTaskName}">
</local:TextBoxChangeExt>
<Button HorizontalAlignment="Right"
Width="57"
d:LayoutOverrides="HorizontalAlignment, Height"
Content="Start"
Command="{Binding StartCommand}" IsEnabled="{Binding StartNewEnabled}"/>
</Grid>
</Grid>
<Grid DockPanel.Dock="Bottom">
<ListBox Margin="8,8,5,5"
BorderBrush="{x:Null}"
ItemTemplate="{DynamicResource TaskTemplate}"
ItemsSource="{Binding SelectedTimeSheet.Tasks}"
HorizontalContentAlignment="Stretch"
/>
</Grid>
</DockPanel>
</DockPanel>

I'm pretty sure this is a bug. I'm getting the same error, and when following the stack-trace to the line in my ViewModel, I see that I'm appropriately checking for null. Everything seems to work during run-time, but I think this is a bug when using implimentations of iCommand in designer.
Let us know if you found your cause to be different.
I'm also using VS 2010.

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.

Databinding custom objects

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

Binding not working inside the content presenter when its visibility is switched from collapsed state to visible state

When the Visibility of ContentPresenter is set to Collapsed and change its Visibility at runtime, breaking the binding of the element kept inside its content.
XAML
<Grid>
<Button x:Name="button"
Width="100"
Height="20"
Margin="173,23,230,268"
Click="button_Click"
Content="Button" />
<ContentPresenter x:Name="contentPresenter"
Margin="0,62,12,0"
Visibility="Collapsed">
<ContentPresenter.Content>
<StackPanel>
<TextBox x:Name="test2"
Width="200"
Height="20" />
<TextBox Width="200"
Height="20"
Text="{Binding ElementName=test2,
Path=Text,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
</ContentPresenter.Content>
</ContentPresenter>
</Grid>
Code
private void button_Click(object sender, RoutedEventArgs e)
{
if (contentPresenter.IsVisible == false)
{
contentPresenter.Visibility = System.Windows.Visibility.Visible;
}
else if (contentPresenter.IsVisible == true)
{
contentPresenter.Visibility = System.Windows.Visibility.Collapsed;
}
}
Any one help.
if you put your content into a usercontrol your binding will work. if you check your output at runtime you would see that there is a binding error. meaning there is no element with "test2"
<Grid>
<Button x:Name="button"
Width="100"
Height="20"
Margin="173,23,230,268"
Click="button_Click"
Content="Button" />
<ContentPresenter x:Name="contentPresenter"
Margin="0,62,12,0"
Visibility="Collapsed">
<ContentPresenter.Content>
<WpfApplication1:UserControl1/>
</ContentPresenter.Content>
</ContentPresenter>
</Grid>
usercontrol
<UserControl x:Class="WpfApplication1.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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<StackPanel>
<TextBox x:Name="test2"
Width="200"
Height="20" />
<TextBox Width="200"
Height="20"
Text="{Binding ElementName=test2,
Path=Text,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
</Grid>
</UserControl>

Binding a textbox from a secondary window is not updating the property

I need to bind the text property of a textbox that it is located in a secondary window to a property that is defined in the corresponding view model of that secondary window
XAML CODE:
<Window x:Class="RG.IOManager.Views.PreferencesDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:genericClasses="clr-namespace:RG.IOManager.GenericClasses"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
Title="Setup" Height="131" Width="332"
WindowStartupLocation="CenterOwner"
ShowInTaskbar="False"
WindowStyle="ToolWindow"
>
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="../ResourceDictionary.xaml" />
<ResourceDictionary Source="../ScrollBarTemplate.xaml" />
<ResourceDictionary Source="../Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="10*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label Content="Cycle Time" Grid.Row="0" Grid.Column="0" Height="28" HorizontalAlignment="Left" Margin="10,10,0,20" Name="label1" VerticalAlignment="Top" />
<StackPanel Grid.Row="0" Grid.Column="1" Width="190" Orientation="Horizontal">
<!--
<xctk:IntegerUpDown Name="TbMainCycleTime" Margin="10,10,0,20" Width="50" Height="25" HorizontalContentAlignment="Right"
Increment="1" Maximum="5000" Minimum="0" ShowButtonSpinner="False"/>
-->
<TextBox Name="TbMainCycleTime" Margin="10,10,0,20" Width="50" Height="25" HorizontalContentAlignment="Right" Validation.ErrorTemplate="{StaticResource ErrorTemplate}" Style="{StaticResource textBoxErrorTooltip}" >
<TextBox.Text>
<Binding Source="PreferencesDialog" Path="CycleTime" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<genericClasses:IntegersValidation Min="0" Max="1000" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<!--<TextBox Name="TbMainCycleTime" Margin="10,10,0,20" Width="50" Height="25" HorizontalContentAlignment="Right" />-->
<Label Content="ms" Margin="1,10,10,20"/>
</StackPanel>
<StackPanel Grid.Row="1" Grid.Column="1" Width="190" Orientation="Horizontal">
<Button Content="Update" Height="23" HorizontalAlignment="Left" Margin="5,0,10,0" Name="btUpdate" VerticalAlignment="Top" Width="75" Click="btUpdate_Click" />
<Button Content="Cancel" Height="23" HorizontalAlignment="Left" Margin="5,0,10,0" Name="btCancel" VerticalAlignment="Top" Width="75" Click="btCancel_Click" />
</StackPanel>
</Grid>
CS CODE:
/// <summary>
/// Interaction logic for PreferencesDialogue.xaml
/// </summary>
public partial class PreferencesDialog : Window, INotifyPropertyChanged
{
#region Binding Properties
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Main cycle time
/// </summary>
public int CycleTime
{
get { return _CycleTime; }
set
{
_CycleTime = value;
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs("CycleTime"));
}
}
}
private int _CycleTime;
#endregion
private IOManager _receiver;
public PreferencesDialog(IOManager receiver)
{
this._receiver = receiver;
InitializeComponent();
//this.TbMainCycleTime.Text = _receiver.globalBindingProperties.MainCycleTime.ToString();
this.CycleTime = _receiver.globalBindingProperties.MainCycleTime;
}
private void btUpdate_Click(object sender, RoutedEventArgs e)
{
_receiver.globalBindingProperties.MainCycleTime = Convert.ToInt32(this.TbMainCycleTime.Text);
this.Close();
}
private void btCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
Can someone help me to find what i did wrong? Thanks in advance
your approach is wrong. however if you change these two thing your problem will be solved:
first set DataContext of the Window:
public PreferencesDialog(IOManager receiver)
{
this.DataContext = this;
this._receiver = receiver;
InitializeComponent();
//this.TbMainCycleTime.Text = _receiver.globalBindingProperties.MainCycleTime.ToString();
this.CycleTime = _receiver.globalBindingProperties.MainCycleTime;
}
second remove 'Source' from TextBox.Text.Binding since the source is the dataContext.
<TextBox Name="TbMainCycleTime" Margin="10,10,0,20" Width="50" Height="25" HorizontalContentAlignment="Right" Validation.ErrorTemplate="{StaticResource ErrorTemplate}" Style="{StaticResource textBoxErrorTooltip}" >
<TextBox.Text>
<Binding Path="CycleTime" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<genericClasses:IntegersValidation Min="0" Max="1000" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
Have you assigned your viewmodel as datacontext to window? (class in which you have defined CycleTime)
Secondly, are you going to change cycle time for UI. You are using two way binding between TextBox and CycleTime property.
Check if this link, where I've created type safe text box extnsions. Though, article is about silverlight, you can easily use in WPF.
Change your xaml as
<Window x:Class="RG.IOManager.Views.PreferencesDialog" x:Name="PreferencesDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

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