Different values for screen size and wpf-window size - c#

i stumbled across a curiosity in WPF which i couldn't explain myself an which i couldn't solve by searching online. So i hope one of you is able to give me a hint to understand my mistake.
Problem: The wpf-window dimensions seems to be 16 units bigger than the screen-resolution. The 16 pixels/units are independent from dimension (windowwidth, windowheight) and screen resolution.
The Problem is shown in the following Application:
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="250" Width="350">
<DockPanel Margin="10,10,0,0">
<DockPanel Width="152" DockPanel.Dock="Top" VerticalAlignment="Top" HorizontalAlignment="Left">
<TextBlock x:Name="displayHeight" HorizontalAlignment="Left" Margin="0,5,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="60"/>
<Label Content="Displayheight" HorizontalAlignment="Left" VerticalAlignment="Top" Height="30"/>
</DockPanel>
<DockPanel Width="148" DockPanel.Dock="Top" VerticalAlignment="Top" HorizontalAlignment="Left">
<TextBlock x:Name="displayWidth" HorizontalAlignment="Left" Margin="0,5,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="60"/>
<Label Content="Displaywidth" HorizontalAlignment="Left" VerticalAlignment="Top" Height="30"/>
</DockPanel>
<DockPanel Width="162" DockPanel.Dock="Top" VerticalAlignment="Top" HorizontalAlignment="Left">
<TextBlock HorizontalAlignment="Left" Margin="0,5,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Text="{Binding ActualHeight, Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" Width="60"/>
<Label Content="Windowheight" HorizontalAlignment="Left" VerticalAlignment="Top" Height="30" Width="92"/>
</DockPanel>
<DockPanel Width="153" DockPanel.Dock="Top" VerticalAlignment="Top" HorizontalAlignment="Left">
<TextBlock HorizontalAlignment="Left" Margin="0,5,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Text="{Binding ActualWidth, Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" Width="60"/>
<Label Content="Windowwidth" HorizontalAlignment="Left" VerticalAlignment="Top" Height="30"/>
</DockPanel>
</DockPanel>
</Window>
C#:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using System.Windows.Forms;
using System.Drawing;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
IntPtr ownerHandle = Process.GetCurrentProcess().MainWindowHandle;
WpfScreen currentScreen = WpfScreen.GetScreenFrom(ownerHandle);
Rect workingArea = currentScreen.WorkingArea;
this.displayHeight.Text = workingArea.Height.ToString();
this.displayWidth.Text = workingArea.Width.ToString();
}
}
public class WpfScreen
{
public static WpfScreen GetScreenFrom(IntPtr windowIntPTR)
{
Screen screen = System.Windows.Forms.Screen.FromHandle(windowIntPTR);
WpfScreen wpfScreen = new WpfScreen(screen);
return wpfScreen;
}
private readonly Screen screen;
internal WpfScreen(System.Windows.Forms.Screen screen)
{
this.screen = screen;
}
public Rect WorkingArea
{
get { return this.GetRect(this.screen.WorkingArea); }
}
private Rect GetRect(Rectangle value)
{
return new Rect
{
X = value.X,
Y = value.Y,
Width = value.Width,
Height = value.Height
};
}
}
}
Basically the code is needed to set the max-Values for Height/Width of an Excel-Addin to the available working area of the display. The above application is just a very simple example to illustrate the problem.
For me it would be ok to just know that the 16 pixels are universally valid and independent from hard-/software. Nevertheless it would be great to get an Explanation whats the reason for this behaviour.
Greetings and THX in advance,
Sven

Why not use
WPF WindowState="Maximized"
see: How can I make a WPF window maximized on the screen with the mouse cursor?

Related

Change the background of the button that is used as a TabItem Header

I using code from a tutorial to develop a GUI with Tab Menu in WPF. Here, the buttons act as the Tab Menu header and every button is linked with an id. Based on the user selection, the id changes which in turn triggers what is displayed when a particular button is clicked. I want to change the background of the button, if it is selected. How can this be done?
Following is the xaml code:
<StackPanel Background="WhiteSmoke">
<Grid Height="40">
<StackPanel HorizontalAlignment="Left" Margin="20 0">
<ComboBox FontSize="15" Width="50" Foreground="#FFA2A2A2" SelectedIndex="0" VerticalAlignment="Center">
<ComboBoxItem Content="EN"/>
</ComboBox>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="20 0">
<Button Content="FAQ" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FFA2A2A2" FontSize="15" FontWeight="Bold" VerticalAlignment="Center"/>
<Button Content="CONTACT" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FFA2A2A2" FontSize="15" FontWeight="Bold" VerticalAlignment="Center"/>
<Button Content="ORDER STATUS" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FFA2A2A2" FontSize="15" FontWeight="Bold" VerticalAlignment="Center"/>
<Button Content="MY ACCOUNT" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FFA2A2A2" FontSize="15" FontWeight="Bold" VerticalAlignment="Center"/>
</StackPanel>
</Grid>
<Grid Height="100">
<StackPanel Orientation="Horizontal" VerticalAlignment="Top" Margin="10 0">
<Button x:Name="b1" Uid="0" Width="150" Content="HOME" Height="50" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FF2196F3" Click="Button_Click"/>
<Button Uid="1" Width="150" Content="SHOP" Height="50" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FF2196F3" Click="Button_Click"/>
<Button Uid="2" Width="150" Content="BLOG" Height="50" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FF2196F3" Click="Button_Click"/>
<Button Uid="3" Width="150" Content="PAGES" Height="50" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FF2196F3" Click="Button_Click"/>
<Button Uid="4" Width="150" Content="PRODUCTS" Height="50" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FF2196F3" Click="Button_Click"/>
<Button Uid="5" Width="150" Content="BRANDS" Height="50" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FF2196F3" Click="Button_Click"/>
<Button Uid="6" Width="150" Content="GIFT CARDS" Height="50" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#FF2196F3" Click="Button_Click"/>
</StackPanel>
<Grid x:Name="GridCursor" Width="150" Height="5" Background="#FF2196F3" HorizontalAlignment="Left" Margin="10 0"/>
</Grid>
<Grid x:Name="GridMain" Height="460" Background="Aquamarine">
</Grid>
</StackPanel>
Following is the code behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
int index = int.Parse(((Button)e.Source).Uid);
GridCursor.Margin = new Thickness(10 + (150 * index), 0, 0, 0);
switch (index)
{
case 0:
GridMain.Background = Brushes.Aquamarine;
b1.Background = Brushes.Yellow;
break;
case 1:
GridMain.Background = Brushes.Beige;
break;
case 2:
GridMain.Background = Brushes.CadetBlue;
break;
case 3:
GridMain.Background = Brushes.DarkBlue;
break;
case 4:
GridMain.Background = Brushes.Firebrick;
break;
case 5:
GridMain.Background = Brushes.Gainsboro;
break;
case 6:
GridMain.Background = Brushes.HotPink;
break;
}
}
I am able to change the background if the button is selected using b1.Background = Brushes.Yellow; . However, the background doesn't change to default when a different button is selected. Also, I am not able to set the background of the button (Uid =1) with which the GUI is launched.
I'm using the community toolkit mvvm for this sample below. I'm not sure this does exactly what you're asking but the binding and templating demonstrates the mvvm approach.
My mainwindow - no buttons.
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ListBox ItemsSource="{Binding Choices}"
x:Name="lb"
>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Width="160">
<Grid.RowDefinitions>
<RowDefinition Height="22"/>
<RowDefinition Height="12"/>
</Grid.RowDefinitions>
<Rectangle Fill="Yellow">
<Rectangle.Style>
<Style TargetType="Rectangle">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger
Binding="{Binding RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType={x:Type ListBoxItem}},
Path=IsSelected}"
Value="True">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Rectangle.Style>
</Rectangle>
<TextBlock Text="{Binding Description}"
TextAlignment="Center"
/>
<Border Grid.Row="1"
CornerRadius="10"
>
<Border.Background>
<SolidColorBrush Color="{Binding BackgroundBrushName}"/>
</Border.Background>
</Border>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Rectangle Grid.Row="1">
<Rectangle.Fill>
<SolidColorBrush Color="{Binding SelectedItem.BackgroundBrushName, ElementName=lb}"/>
</Rectangle.Fill>
</Rectangle>
</Grid>
</Window>
Mainwindowviewmodel
public partial class MainWindowViewModel : ObservableObject
{
public List<Choice> Choices { get; set; } = new List<Choice>
{
new Choice{ Description = "Shop", BackgroundBrushName = "Red"},
new Choice{ Description = "Blog", BackgroundBrushName = "Blue"},
new Choice{ Description = "Products", BackgroundBrushName = "Green"}
};
}
Choice
public partial class Choice : ObservableObject
{
public string BackgroundBrushName { get; set; }
[ObservableProperty]
private string description = string.Empty;
}
None of those properties change but you should always implement inotifypropertychanged on any viewmodel and ObservableObject adds that. description does not change so it doesn't really need change notification but I thought it would be interesting to see the code generator creates a Description property for you.
The collection is templated out into UI. The "menu" is a horizontal listbox which has the selector behaviour so you can click one and it is selected.
The background for the selected choice is usually visibility collapsed but a datatrigger sets it to visible if it's in the selected item.
We could also bind selecteditem mode=twoway and set that to the first choice if we wanted an initial one....errm... chosen.
Hopefully this gives you a reasonably beginner friendly introduction to mvvm techniques.

Where do File Parsers belong in MVVM Design Pattern?

I have tried to find a good consistent folder structure in Visual Studio to capture all the possibilities. This so far has been what I've came up with for my project.
My Application looks like:
The xaml is pretty straight forward:
<Window x:Class="Check.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewModels="clr-namespace:SA_BOM_Check.ViewModels"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance Type=viewModels:MainWindowViewModel, IsDesignTimeCreatable=True}"
Height="600" Width="800"
DataContext="{StaticResource ResourceKey=MainWindowViewModel}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="40"></RowDefinition>
<RowDefinition Height="40"></RowDefinition>
<RowDefinition Height="10"></RowDefinition>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Grid.Row="1" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Right" Text="XA File: " Height="30" FontSize="20" FontWeight="Bold"/>
<TextBox x:Name="TxtXAFile" Grid.Row="1" Grid.Column="1" Text="{Binding Path=XAFile, Mode=TwoWay}" VerticalAlignment="Center" FontSize="15"></TextBox>
<Button x:Name="BtnXaBrowse" Grid.Row="1" Grid.Column="2" VerticalAlignment="Center" Margin="10,5,80,1" FontSize="20" FontWeight="DemiBold" Click="BtnXaBrowse_OnClick">Browse...</Button>
<TextBlock Grid.Row="2" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Right" Text="Inventor File: " Height="30" FontSize="20" FontWeight="Bold"/>
<TextBox Grid.Row="2" Grid.Column="1" x:Name="TxtInventorFile" Text="{Binding Path=InventorFile, Mode=TwoWay}" VerticalAlignment="Center" FontSize="15"/>
<Button x:Name="BtnInventorBrowse" Grid.Row="2" Grid.Column="2" VerticalAlignment="Center" Margin="10,0,80,0" FontSize="20" FontWeight="DemiBold" Click="BtnInventorBrowse_OnClick">Browse...</Button>
<Button x:Name="BtnDiff" Grid.Row="2" Grid.Column="3" VerticalAlignment="Center" Margin="10,5,80,1" FontSize="20" FontWeight="DemiBold" Command="{Binding GetDifferences}">Differences</Button>
<Line Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="4" X1="0" Y1="0" X2="1" Y2="0" Stroke="Black" StrokeThickness="2" Stretch="Uniform"></Line>
<Label Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="4" Content="Missing in Inventor (Inventor - XA)" FontSize="15" FontStyle="Normal" HorizontalAlignment="Center" FontWeight="Bold" Foreground="Black"/>
<DataGrid AutoGenerateColumns="True" Grid.Row="5" Grid.Column="0" Grid.ColumnSpan="4" IsReadOnly="True"
FontSize="18" ItemsSource="{Binding Path=XADiffDataTable}"
ColumnWidth="*">
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="FontWeight" Value="Bold"></Setter>
</Style>
</DataGrid.ColumnHeaderStyle>
</DataGrid>
<Label Grid.Row="6" Grid.Column="0" Grid.ColumnSpan="4"
Content="Missing In XA (XA - Inventor)" FontSize="15" FontStyle="Normal"
HorizontalAlignment="Center" FontWeight="Bold" Foreground="Black"/>
<DataGrid Grid.Row="7" Grid.Column="0" Grid.ColumnSpan="4"
AutoGenerateColumns="True" IsReadOnly="True"
FontSize="18" ItemsSource="{Binding Path=InventorDiffDataTable}"
ColumnWidth="*">
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="FontWeight" Value="Bold"></Setter>
</Style>
</DataGrid.ColumnHeaderStyle>
</DataGrid>
</Grid>
</Window>
Code Behind:
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;
using SA_BOM_Check.ViewModels;
namespace SA_BOM_Check.Views
{
public partial class MainWindow : Window
{
//private readonly MainWindowViewModel _vm;
public MainWindow()
{
InitializeComponent();
//_vm = (MainWindowViewModel) this.DataContext;
}
private void BtnXaBrowse_OnClick(object sender, RoutedEventArgs e)
{
TxtXAFile.Text = OpenFileDialog();
TxtXAFile.GetBindingExpression(TextBox.TextProperty)?.UpdateSource();
//_vm.XAFile = OpenFileDialog();
}
private void BtnInventorBrowse_OnClick(object sender, RoutedEventArgs e)
{
TxtInventorFile.Text = OpenFileDialog();
TxtInventorFile.GetBindingExpression((TextBox.TextProperty))?.UpdateSource();
}
private string OpenFileDialog()
{
OpenFileDialog openFileDialog = new();
return openFileDialog.ShowDialog() == true ? openFileDialog.FileName : "";
}
}
}
Keeping the ShowDialog inside the code behind was inspired by BionicCode https://stackoverflow.com/users/3141792/bioniccode
Where he answered the question about OpenFileDialogs Open File Dialog MVVM Actual Answer (which should have been the answer to the question) is at https://stackoverflow.com/a/64861760/4162851
The InventorAndXACompare class in summary is
private static readonly Dictionary<string, Part> INVENTOR_PARTS
= new Dictionary<string, Part>();
private static readonly Dictionary<string, Part> XA_PARTS = new Dictionary<string, Part>();
private static readonly Dictionary<string, Part> XA_PARTS_OMIT = new Dictionary<string, Part>();
private static readonly DataTable MISSING_IN_INVENTOR = new DataTable("XACompared");
private static readonly DataTable MISSING_IN_XA = new DataTable("InventorCompared");
public static DataTable[] CompareFiles(string xaFile, string inventorFile)
private static void ParseInventor(string inventorFile)
private static void ParseXA(string xaFile)
private static void CompareXAToInventor()
private static void CompareInventorToXA()
The compare files takes two files. It then parses those files into two dictionaries that are compared in both directions where there are differences it adds those rows to a datatable inside the MainWindowViewModel those are then binded to the View by
private DataTable _xaDiffDataTable;
public DataTable XADiffDataTable
{
get { return _xaDiffDataTable;}
set
{
_xaDiffDataTable = value;
OnPropertyChanged("XADiffDataTable");
}
}
private DataTable _inventorDiffDataTable;
public DataTable InventorDiffDataTable
{
get { return _inventorDiffDataTable;}
set
{
_inventorDiffDataTable = value;
OnPropertyChanged("InventorDiffDataTable");
}
}
I would like to know if there is a better way of structuring this and if InventorAndXACompare would be better placed in the Models folder?
In an MVVM architecture you would usually find parsers in the Model component. The View Model generally does not process data. Usually it may convert data to meet the constraints of the Model's interface or to prepare data for presentation in the View.
Also from an MVVM point of view the data source and sink is always part of the Model. It does not matter whether data comes from a database or from a file picked by the user.

how to properly use item click in gridview

I have a gridview, which presents all of the users I have in my database, and their details, I want to be able, on the click of a user(on the gridview), that it's details will appear separately on the side of the grid view, and there I could change them accordingly. However, I'm not sure how to do so. I have the ItemClick event in my gridview, and It does recognize if I click on an item, but I don't know how to get that specific clicked user's details, for me to present them on the side. I also have another problem- for some reason It doesn't recognize nor let me click on any of the top row items on the grid view-only the ones below it, does anyone know why?
this is my XAML :
<Page
x:Class="My_Little_Animal.ShowUsers"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:My_Little_Animal"
xmlns:data="using:My_Little_Animal"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<Grid.Background>
<ImageBrush ImageSource="/Assets/changeUserDetailesBackground.jpg"></ImageBrush>
</Grid.Background>
<Grid.RowDefinitions>
<RowDefinition Height="8*" />
<RowDefinition Height="147*"/>
<RowDefinition Height="100" />
</Grid.RowDefinitions>
<GridView Name="grid1" ItemClick="grid1_ItemClick" IsItemClickEnabled="True" Margin="-70,151,692,50" Grid.RowSpan="2" Grid.Row="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<GridView.ItemTemplate>
<DataTemplate x:DataType="data:User">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
<StackPanel Margin="100,20,0,0">
<TextBlock Name="t1" FontSize="20" GotFocus="t1_GotFocus" Text="{x:Bind UserId}"/>
<TextBlock Name="t2" FontSize="20" GotFocus="t2_GotFocus" Text="{x:Bind Password}"/>
<TextBlock Name="t3" FontSize="20" GotFocus="t3_GotFocus" Text="{x:Bind UserName}"/>
<TextBlock Name="t4" FontSize="20" GotFocus="t4_GotFocus" Text="{x:Bind Email}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
<Canvas>
<Image Name="loginTitle" Source="/Assets/ShowUsersTitle.png" RenderTransformOrigin="0.5,0.5" Grid.RowSpan="2" Canvas.Left="-325" Canvas.Top="-120" Height="462" Width="1875"/>
<TextBlock Grid.Row="2" Name="ResultTextBlock" FontSize="24" Foreground="Red" FontWeight="Bold" Height="169" Margin="0,0,0,-69"/>
<Image Name="editTheUserName" Width="100" Height="35" Visibility="Visible" Source="/Assets/editIcon.png" RenderTransformOrigin="0.5,0.5" Grid.Row="1" Canvas.Left="852" Canvas.Top="226" />
<Image Name="CancelTheUserNamE" Width="100" Height="35" Visibility="Visible" Source="/Assets/xIcon.png" RenderTransformOrigin="0.485,0.529" Grid.Row="1" Canvas.Left="848" Canvas.Top="224" />
<TextBlock Visibility="Visible" Name="theUserItself" FontFamily="Comic Sans MS" FontWeight="ExtraBold" FontStyle="Italic" FontSize="25" Text="your user name " RenderTransformOrigin="0.496,1.165" Foreground="#FF283D6C" Grid.Row="1" Canvas.Left="1103" Canvas.Top="219" HorizontalAlignment="Stretch" Margin="0,0,0,0" VerticalAlignment="Stretch"/>
<TextBlock Name="userName" FontFamily="Comic Sans MS" FontWeight="ExtraBold" FontStyle="Italic" FontSize="25" Text="User Name : " RenderTransformOrigin="0.496,1.165" TextDecorations="Underline" Grid.Row="1" Canvas.Left="922" Canvas.Top="224"/>
<TextBox Visibility="Visible" Width="200" Name="UserNameText" MaxLength="50" FontFamily="Comic Sans MS" FontStyle="Italic" FontSize="15" BorderThickness="3" BorderBrush="#FF23677D" Grid.Row="1" Canvas.Left="1099" Canvas.Top="223" HorizontalAlignment="Stretch" Margin="0,0,0,0" VerticalAlignment="Stretch"/>
<Button Visibility="Visible" Name="changeuserName" Height="49" Width="140" FontSize="20" Content="change" FontWeight="ExtraBold" BorderBrush="White" Foreground="White" BorderThickness="2" Background="#FF191A5C" HorizontalAlignment="Center" VerticalAlignment="Top" RenderTransformOrigin="0.45,0.536" Grid.Row="1" Canvas.Left="1305" Canvas.Top="210" Margin="0,0,0,0"/>
<Image Name="editTheEmail" Canvas.Top="286" Canvas.Left="850" Width="100" Height="35" Visibility="Visible" Source="/Assets/editIcon.png" RenderTransformOrigin="0.49,0.557" Grid.Row="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
<Image Name="CancelTheEmail" Width="100" Height="35" Visibility="Visible" Source="/Assets/xIcon.png" RenderTransformOrigin="0.485,0.529" Grid.Row="1" Canvas.Left="847" Canvas.Top="284" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
<TextBlock Visibility="Visible" Name="theEmailItself" FontFamily="Comic Sans MS" FontWeight="ExtraBold" FontStyle="Italic" FontSize="25" Text="your email " RenderTransformOrigin="0.496,1.165" Foreground="#FF283D6C" Grid.Row="1" Canvas.Left="1105" Canvas.Top="276"/>
<TextBlock Name="Email" FontFamily="Comic Sans MS" FontWeight="ExtraBold" FontStyle="Italic" FontSize="25" Text="Email : " RenderTransformOrigin="0.496,1.165" TextDecorations="Underline" Grid.Row="1" Canvas.Left="921" Canvas.Top="283" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
<TextBox Visibility="Visible" Width="200" Name="EmailText" MaxLength="50" FontFamily="Comic Sans MS" FontStyle="Italic" FontSize="15" BorderThickness="3" BorderBrush="#FF23677D" Grid.Row="1" Canvas.Left="1093" Canvas.Top="284" HorizontalAlignment="Stretch" Margin="0,0,0,0" VerticalAlignment="Stretch"/>
<Button Visibility="Visible" Name="changeEmail" Height="49" Width="140" FontSize="20" Content="change" FontWeight="ExtraBold" BorderBrush="White" Foreground="White" BorderThickness="2" Background="#FF191A5C" HorizontalAlignment="Center" VerticalAlignment="Top" RenderTransformOrigin="0.45,0.536" Grid.Row="1" Canvas.Left="1302" Canvas.Top="274" Margin="0,0,0,0"/>
<Image Name="theReturn" Height="100" Width="100" Tapped="theReturn_Tapped_1" Source="/Assets/theReturnIcon.png" RenderTransformOrigin="0.493,0.496" Grid.RowSpan="2" Canvas.Left="65" Canvas.Top="27" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</Canvas>
</Grid>
The c# code :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Xml;
using System.Data;
using Windows.UI.Popups;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238
namespace My_Little_Animal
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class ShowUsers : Page
{
regitration.regitrationSoapClient cal;
public ShowUsers()
{
this.InitializeComponent();
cal = new regitration.regitrationSoapClient();
getData();
}
public async void getData()
{
regitration.getUserTableResponseGetUserTableResult r = await cal.getUserTableAsync();
List<User> theUserList = new List<User>();
User u = null;
XmlReader xr = r.Any1.CreateReader();
XmlDocument document = new XmlDocument();
document.Load(xr);
XmlNodeList theXmlList = document.GetElementsByTagName("Table");
foreach (XmlElement item in theXmlList)
{
u = new User();
foreach (XmlNode node in item.ChildNodes)
{
switch (node.Name)
{
case "userId": u.UserId = int.Parse(node.InnerText); break;
case "password": u.Password = node.InnerText; break;
case "userName": u.UserName = node.InnerText; break;
case "email": u.Email = node.InnerText; break;
}
}
theUserList.Add(u);
}
grid1.ItemsSource = theUserList;
}
private async void grid1_ItemClick(object sender, ItemClickEventArgs e)
{
var dialog = new MessageDialog("The item that was clicked is : ");
await dialog.ShowAsync();
}
private void t1_GotFocus(object sender, RoutedEventArgs e)
{
}
private void t2_GotFocus(object sender, RoutedEventArgs e)
{
}
private void t3_GotFocus(object sender, RoutedEventArgs e)
{
}
private void t4_GotFocus(object sender, RoutedEventArgs e)
{
}
private void theReturn_Tapped_1(object sender, TappedRoutedEventArgs e)
{
this.Frame.Navigate(typeof(Administrator));
}
}
}
I will be so thankful for any help, it's really important for me!
but I don't know how to get that specific clicked user's details, for me to present them on the side.
There are many ways to get the item in item click event. if you have used MVVM pattern, the recommend way is binding command. For more you could refer this case.
In general, you could subscribe ItemClick event and get ClickedItem from event ItemClickEventArgs
Example
private void VideoGridView_ItemClick(object sender, ItemClickEventArgs e)
{
var vedio = e.ClickedItem as VideoItem;
var item = new MediaPlaybackItem(MediaSource.CreateFromUri(new Uri(vedio.videoUri)));
mediaPlayerElement.Source = item;
}
I also have another problem- for some reason It doesn't recognize nor let me click on any of the top row items on the grid view-only the ones below it, does anyone know why?
I could not reproduce this issue, please check if there is some element cover the top row up cause the grid view could not be clicked.

Bind Labels to selected item in WPF C#

It's possible that my question has already been answered but I want to see if I can fix the problem in my own context.
The problem is that I have a ListBox containing cars, if you check the code you see that there is a GridView with Labels in it, these labels get the first item (first car) but I want it to get the car that you select in the ListBox.
As I said, there may already be an answer that I haven't found yet but any help would be appreciated!
<Window x:Class="WBS.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:WBS"
mc:Ignorable="d" x:Name="mainWindow"
Title="MainWindow" Height="353.2" Width="696.2">
<Grid Margin="0,0,0,0" Background="#FFDFE4E3">
<Button x:Name="btInfo" Content="Filter" HorizontalAlignment="Left" Margin="336,132,0,0" VerticalAlignment="Top" Width="75" Click="btInfo_Click"/>
<Button x:Name="btEditCar" Content="Bewerk" HorizontalAlignment="Left" Margin="336,92,0,0" VerticalAlignment="Top" Width="75" Click="btEditCar_Click"/>
<ListBox x:Name="lbCars" HorizontalAlignment="Left" Height="140" Margin="184,50,0,0" VerticalAlignment="Top" Width="142"/>
<Button x:Name="btAddCar" Content="Voeg toe" HorizontalAlignment="Left" Margin="336,50,0,0" VerticalAlignment="Top" Width="75" Click="btAddCar_Click"/>
<ListBox x:Name="lbFleets" HorizontalAlignment="Left" Height="140" Margin="10,50,0,0" VerticalAlignment="Top" Width="144" SelectionChanged="lbFleets_SelectionChanged"/>
<Grid Margin="515,50,9.6,53.6" Name="grdCarOverview" Background="#FF91908F">
<Label x:Name="lbBrand" Content="{Binding Path=[0].Brand}" HorizontalAlignment="Left" Margin="10,42,0,0" VerticalAlignment="Top" Height="27" Width="146" BorderBrush="#FFB3B3B3" BorderThickness="1"/>
<Label x:Name="lbColor" Content="{Binding Path=[0].Color}" HorizontalAlignment="Left" Margin="10,74,0,0" VerticalAlignment="Top" Height="30" Width="146" BorderThickness="1" BorderBrush="#FFB3B3B3"/>
<Label x:Name="lbConstructionYear" Content="{Binding Path=[0].ConstructionYear}" HorizontalAlignment="Left" Margin="10,112,0,0" VerticalAlignment="Top" Height="85" Width="146" FontSize="36" FontWeight="Bold" BorderBrush="#FFB3B3B3" BorderThickness="1"/>
<Label Content="De eerste auto:" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10,10,0,0"/>
</Grid>
<Label Content="Lijst met vloten:" HorizontalAlignment="Left" Margin="10,19,0,0" VerticalAlignment="Top" Width="110"/>
<Label Content="Lijst auto's per vloot:" HorizontalAlignment="Left" Margin="184,19,0,0" VerticalAlignment="Top"/>
<Button x:Name="btAddFleet" Content="Voeg toe" HorizontalAlignment="Left" Margin="36,206,0,0" VerticalAlignment="Top" Width="75" Click="btAddFleet_Click"/>
<Button x:Name="btEditFleet" Content="Bewerk" HorizontalAlignment="Left" Margin="36,242,0,0" VerticalAlignment="Top" Width="75" Click="btEditFleet_Click"/>
<Button x:Name="btRemoveCar" Content="Verwijder" HorizontalAlignment="Left" Margin="336,171,0,0" VerticalAlignment="Top" Width="75" Click="btRemoveCar_Click"/>
<Button x:Name="btRemoveFleet" Content="Verwijder" HorizontalAlignment="Left" Margin="36,277,0,0" VerticalAlignment="Top" Width="75" Click="btRemoveFleet_Click"/>
</Grid>
</Window>
CS:
public ObservableCollection<Car> Cars { get; set; }
public Car SelectedCar { get; set; }
public ObservableCollection<Fleet> Fleets { get; set; }
You need to add binding to your ListBox control
<ListBox x:Name="lbCars"
ItemsSource="{Binding Cars }"
SelectedValue="{Binding SelectedCarId}"
SelectedValuePath="Id" DisplayMemberPath="Name"
HorizontalAlignment="Left"
Height="140" Margin="184,50,0,0"
VerticalAlignment="Top" Width="142"/>
in CS file ,making dummy data
public ObservableCollection<Car> Cars = new ObservableCollection<Car>
{
new Car{Id = 0, Name = "Audi"},
new Car{Id = 1, Name = "Honda"},
new Car{Id = 2, Name = "Toyota"},
};
public int SelectedCarId { get; set; }
SelectedCarId will hold the Id of Car selected.
Same goes for lbFleets ListBox as well.

Enabled View after login my application

I am a beginner in WPF /MVVM and I have a lot of problems..
One of theses, it that I've an application with a LoginView on the left and a content view on the left.
Theses 2 views are in the MainView like this :
First View "MainWindow"
<Window x:Class="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:iut1"
xmlns:ctrls="clr-namespace:iut1.Views"
mc:Ignorable="d"
Title="Outil de pilotage SCR" Height="650" Width="950"
WindowStartupLocation="CenterScreen"
DataContext="{Binding Path=MainWindowViewModel, Mode=OneWay, Source={StaticResource Locator}}">
<Grid>
<Viewbox Name="vbxConnexion" HorizontalAlignment="Left" Height="623" VerticalAlignment="Top" Width="224">
<ctrls:ConnexionView></ctrls:ConnexionView>
</Viewbox>
<Viewbox Name="vbxContenu" HorizontalAlignment="Left" Margin="233,0,0,0" Width="682" VerticalAlignment="Top" RenderTransformOrigin="0.5,0.5" Height="620" Stretch="None">
<ctrls:MigrationModeleView IsEnabled="{Binding EnabledView}" Height="623" Width="653" ></ctrls:MigrationModeleView>
</Viewbox>
</Grid>
Seconde View : "ConnexionView"
<UserControl x:Class="iut1.Views.ConnexionView"
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:iut1.Views"
xmlns:w="clr-namespace:iut1.Classes"
mc:Ignorable="d"
d:DesignHeight="720" d:DesignWidth="240"
DataContext="{Binding Path=MainWindowViewModel, Mode=OneWay, Source={StaticResource Locator}}">
<UserControl.Resources>
<w:EnumMatchToBooleanConverter x:Key="enumConverter" />
</UserControl.Resources>
<Grid Margin="10,30,-13,-18">
<GroupBox x:Name="gpbSource" HorizontalAlignment="Left" Margin="6,10,0,386" Width="220" Header="Environnement source" Background="{DynamicResource {x:Static SystemColors.ScrollBarBrushKey}}" >
<Grid Margin="0,0,0,20">
<!--<Rectangle Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="317" VerticalAlignment="Top" Width="220" RadiusY="5" RadiusX="5" Stroke="Black" Opacity="0.1" Margin="0,5,0,0"/>-->
<Label x:Name="lblIdentifiant" Content="Identifiant de l'utilisateur :" HorizontalAlignment="Left" Margin="4,24,0,0" VerticalAlignment="Top" Width="200"/>
<TextBox x:Name="txtNomUsager" Text="{Binding IdUtilisateur}" HorizontalAlignment="Left" Height="23" Margin="4,48,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="200" AutomationProperties.IsRequiredForForm="True" BorderThickness="2">
</TextBox>
<Label x:Name="Password" Content="Mot de passe :" HorizontalAlignment="Left" Margin="4,80,0,0" VerticalAlignment="Top" Width="200"/>
<PasswordBox x:Name="txtMotDePasse" w:PasswordHelper.Attach="True" w:PasswordHelper.Password="{Binding PasswordUtilisateur, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Height="23" Margin="4,103,0,0" VerticalAlignment="Top" Width="200"/>
<RadioButton x:Name="rdbUnit" IsChecked="{Binding Path=EnvironnementSource, Mode=TwoWay,Converter={StaticResource enumConverter}, ConverterParameter=Unitaire}" GroupName="envSource" Width="79" Content="Unitaire" HorizontalAlignment="Left" Margin="4,160,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="rdbFonctionnel" IsChecked="{Binding Path=EnvironnementSource, Mode=TwoWay,Converter={StaticResource enumConverter}, ConverterParameter=Fonctionnel}" Content="Fonctionnel" GroupName="envSource" Width="79" HorizontalAlignment="Left" Margin="4,183,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="rdbIntegre" IsChecked="{Binding Path=EnvironnementSource, Mode=TwoWay,Converter={StaticResource enumConverter}, ConverterParameter=Integre}" GroupName="envSource" Width="79" Content="Intégré" HorizontalAlignment="Left" Margin="4,206,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="rdbAcceptation" IsChecked="{Binding Path=EnvironnementSource, Mode=TwoWay,Converter={StaticResource enumConverter}, ConverterParameter=Acceptation}" GroupName="envSource" Width="90" Content="Acceptation" HorizontalAlignment="Left" Margin="114,162,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="rdbFormation" IsChecked="{Binding Path=EnvironnementSource, Mode=TwoWay,Converter={StaticResource enumConverter}, ConverterParameter=Formation}" GroupName="envSource" Width="90" Content="Formation" HorizontalAlignment="Left" Margin="114,183,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="rdbProduction" IsChecked="{Binding Path=EnvironnementSource, Mode=TwoWay,Converter={StaticResource enumConverter}, ConverterParameter=Production}" GroupName="envSource" Width="90" Content="Production" HorizontalAlignment="Left" Margin="114,206,0,0" VerticalAlignment="Top"/>
<Button x:Name="Login" Content="Connexion" HorizontalAlignment="Left" Margin="4,252,0,0" VerticalAlignment="Top" Width="200" Command="{Binding ButtonCommand}"/>
</Grid>
</GroupBox>
<!--<Rectangle Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="317" VerticalAlignment="Top" Width="220" RadiusY="5" RadiusX="5" Stroke="Black" Opacity="0.1" Margin="0,350,0,-179"/>-->
<GroupBox Width="220" Header="Environnement source" Margin="6,338,17,57" IsEnabled="False" Background="{DynamicResource {x:Static SystemColors.ScrollBarBrushKey}}">
<Grid Margin="0,0,0,20">
<Label x:Name="lblIdentifiantCopie" Content="Identifiant de l'utilisateur :" HorizontalAlignment="Left" Margin="4,24,0,0" VerticalAlignment="Top" Width="200"/>
<TextBox x:Name="txtNomUsagerCopie" HorizontalAlignment="Left" Height="23" Margin="4,47,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="200"/>
<Label x:Name="lblMotDePasseCopie" Content="Mot de passe :" HorizontalAlignment="Left" Margin="4,80,0,0" VerticalAlignment="Top" Width="200"/>
<PasswordBox x:Name="txtMotDePasseCopie" HorizontalAlignment="Left" Height="23" Margin="4,103,0,0" VerticalAlignment="Top" Width="200"/>
<RadioButton x:Name="rdbUnitCopie" Width="79" Content="Unitaire" HorizontalAlignment="Left" Margin="4,160,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="rdbFonctionnelCopie" Width="79" Content="Fonctionnel" HorizontalAlignment="Left" Margin="4,183,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="rdbIntegreCopie" Width="79" Content="Intégré" HorizontalAlignment="Left" Margin="4,206,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="rdbAcceptationCopie" Width="90" Content="Acceptation" HorizontalAlignment="Left" Margin="114,162,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="rdbFormationCopie" Width="90" Content="Formation" HorizontalAlignment="Left" Margin="114,183,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="rdbProductionCopie" Width="90" Content="Production" HorizontalAlignment="Left" Margin="114,206,0,0" VerticalAlignment="Top"/>
<Button x:Name="btnAjout" Content="Ajouter dans l'environnement" HorizontalAlignment="Left" Margin="4,252,0,0" VerticalAlignment="Top" Width="200"/>
</Grid>
</GroupBox>
</Grid>
MigrationModelView
<UserControl x:Class="iut1.Views.MigrationModeleView"
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:iut1.Views"
mc:Ignorable="d" d:DesignWidth="630" Height="587"
xmlns:w="clr-namespace:iut1.Classes"
DataContext="{Binding Path=MainWindowViewModel, Source={StaticResource Locator}}">
<Grid Margin="15,22,0,0">
<GroupBox Header="Migration de modèle de lettre" Margin="6,10,0,32">
<Grid Margin="0,0,0,4">
<Label x:Name="lblChoixPPP" Content="PPP :" HorizontalAlignment="Left" Margin="19,13,0,0" VerticalAlignment="Top"/>
<ComboBox x:Name="cbxChoixPPP" HorizontalAlignment="Left" Margin="67,13,0,0" VerticalAlignment="Top" Width="120"/>
<DataGrid x:Name="dgModeles" HorizontalAlignment="Left" Margin="19,61,0,0" VerticalAlignment="Top" Height="162" Width="565">
<DataGrid.Columns>
<DataGridCheckBoxColumn Header=""/>
<DataGridTextColumn Header="Numéro de référence" Width="150" />
<!--Binding="{Binding Nom}"-->
<DataGridTextColumn Header="Titre du modèle de lettre" />
<!--Binding="{Binding Prenom}"-->
</DataGrid.Columns>
</DataGrid>
<Label x:Name="lblRechercher" Content="Rechercher :" HorizontalAlignment="Left" Margin="19,239,0,0" VerticalAlignment="Top"/>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="91,241,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="291"/>
<Button x:Name="btnAfficherTout" Content="Afficher tout" HorizontalAlignment="Left" Margin="387,244,0,0" VerticalAlignment="Top" Width="96"/>
<Button x:Name="btnAfficherSelection" IsEnabled="False" Content="Afficher sélection" HorizontalAlignment="Left" Margin="488,244,0,0" VerticalAlignment="Top" Width="96"/>
<DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Margin="19,319,0,0" VerticalAlignment="Top" Height="162" Width="565">
<DataGrid.Columns>
<DataGridTextColumn Header="Résultat de la copie" Width="150" />
<DataGridTextColumn Header="" />
</DataGrid.Columns>
</DataGrid>
<ProgressBar HorizontalAlignment="Left" Height="20" Margin="22,509,0,-26" VerticalAlignment="Top" Width="464"/>
<Button x:Name="btnDetails" Height="20" IsEnabled="False" Content="Détails" HorizontalAlignment="Left" Margin="491,509,0,-26" VerticalAlignment="Top" Width="96"/>
</Grid>
</GroupBox>
</Grid>
I would like to enable=true my view after click on the Login button on my ConnexionView.
I tryed a lot of thing and nothing works.
MY VM Code :
using GalaSoft.MvvmLight.CommandWpf;
using iut1.Classes;
using iut1.Interfaces;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
namespace iut1.ViewModels
{
/// <summary>
///
/// </summary>
public class MainWindowViewModel : BaseViewModel, INotifyPropertyChanged
{
#region Proprietes privées
private readonly DelegateCommand<string> _clickCommand;
private string _idUtilisateur;
private string _passwordUtilisateur;
private string _environnementSource;
#endregion Proprietes privées
#region proprietes publiques
public string IdUtilisateur
{
get { return _idUtilisateur; }
set
{
_idUtilisateur = value;
RaisePropertyChanged(nameof(IdUtilisateur));
}
}
public string PasswordUtilisateur
{
get { return _passwordUtilisateur; }
set
{
_passwordUtilisateur = value;
RaisePropertyChanged(nameof(PasswordUtilisateur));
}
}
public string EnvironnementSource
{
get { return _environnementSource; }
set
{
_environnementSource = value;
RaisePropertyChanged(nameof(EnvironnementSource));
}
}
#endregion proprietes publiques
private bool _enabledView;
public bool EnabledView
{
get { return _enabledView; }
set
{
if (_enabledView == value)
{
return;
}
_enabledView = value;
RaisePropertyChanged(nameof(EnabledView));
OnPropertyChanged(nameof(EnabledView));
}
}
public MainWindowViewModel()
{
//ButtonCommand = new Classes.RelayCommand(new Action<object> (ConnectionBase));
ButtonCommand = new Classes.RelayCommand(o => { ConnectionBase(); }, o => true);
//_clickCommand = new DelegateCommand<string>(
// (s) => { ConnectionBase(); /* perform some action */ }
// );
EnabledView =false;
}
public DelegateCommand<string> ButtonClickCommand
{
get { return _clickCommand; }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private void ConnectionBase()
{
if (Validation.ValidationConnection(IdUtilisateur, PasswordUtilisateur, EnvironnementSource))
{
EnabledView = true;
OnPropertyChanged(nameof(EnabledView));
}
else
{
string msgErreur = "KO";
}
}
private void Login(object parameter)
{
//return Validation.ValidationConnection(IdUtilisateur, password, "ENV");
}
private ICommand _buttonCommand;
public ICommand ButtonCommand
{
get
{
return _buttonCommand;
}
set
{
_buttonCommand = value;
}
}
}
}
The problem is that my view nerver become enable and I'm becoming crazy about that.
Thank you in advance for the help.
It is important that you raise the INotifyPropertyChanged event once, and in the correct place, so that all 'subscribers' are aware of the old value and the change to the new value. Because you are raising the event multiple times, I suspect that the 'subscribers' are basically being told that the value has been updated - old value: false, new value: false.
Without seeing the entirety of your solution and latest code, it is tough to accurately diagnose the problem, here is code which I have just refactored from what you have in your original post, clicking the button calls the ButtonCommand which immediately sets the EnabledView property to the opposite of what it currently is, this enables and disables the MigrationModeleView for me.
App.xaml
<Application x:Class="MvvmLight1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:MvvmLight1.ViewModel"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ignore="http://www.galasoft.ch/ignore"
StartupUri="MainWindow.xaml"
mc:Ignorable="d ignore">
<Application.Resources>
<!--Global View Model Locator-->
<vm:ViewModelLocator x:Key="Locator"
d:IsDataSource="True" />
</Application.Resources>
</Application>
MainWindow
<Window x:Class="MvvmLight1.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:ignore="http://www.galasoft.ch/ignore"
xmlns:mvvmLight1="clr-namespace:MvvmLight1"
mc:Ignorable="d ignore"
Height="650"
Width="950"
Title="MVVM Light Application"
DataContext="{Binding Main, Source={StaticResource Locator}}">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Skins/MainSkin.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Viewbox Name="vbxConnexion" HorizontalAlignment="Left" Height="623" VerticalAlignment="Top" Width="224">
<mvvmLight1:ConnexionView></mvvmLight1:ConnexionView>
</Viewbox>
<Viewbox Name="vbxContenu" HorizontalAlignment="Left" Margin="233,0,0,0" Width="682" VerticalAlignment="Top" RenderTransformOrigin="0.5,0.5" Height="620" Stretch="None">
<mvvmLight1:MigrationModeleView IsEnabled="{Binding EnabledView}" Height="623" Width="653" ></mvvmLight1:MigrationModeleView>
</Viewbox>
</Grid>
</Window>
ConnexionView.xaml
<UserControl x:Class="MvvmLight1.ConnexionView"
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:MvvmLight1"
mc:Ignorable="d"
d:DesignHeight="720" d:DesignWidth="240"
DataContext="{Binding Main, Source={StaticResource Locator}}">
<Grid Margin="10,30,-13,-18">
<GroupBox x:Name="gpbSource" HorizontalAlignment="Left" Margin="6,10,0,386" Width="220" Header="Environnement source" Background="{DynamicResource {x:Static SystemColors.ScrollBarBrushKey}}" >
<Grid Margin="0,0,0,20">
<!--<Rectangle Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="317" VerticalAlignment="Top" Width="220" RadiusY="5" RadiusX="5" Stroke="Black" Opacity="0.1" Margin="0,5,0,0"/>-->
<Label x:Name="lblIdentifiant" Content="Identifiant de l'utilisateur :" HorizontalAlignment="Left" Margin="4,24,0,0" VerticalAlignment="Top" Width="200"/>
<TextBox x:Name="txtNomUsager" Text="{Binding IdUtilisateur}" HorizontalAlignment="Left" Height="23" Margin="4,48,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="200" AutomationProperties.IsRequiredForForm="True" BorderThickness="2">
</TextBox>
<Label x:Name="Password" Content="Mot de passe :" HorizontalAlignment="Left" Margin="4,80,0,0" VerticalAlignment="Top" Width="200"/>
<PasswordBox x:Name="txtMotDePasse" HorizontalAlignment="Left" Height="23" Margin="4,103,0,0" VerticalAlignment="Top" Width="200"/>
<RadioButton x:Name="rdbUnit" IsChecked="{Binding Path=EnvironnementSource, Mode=TwoWay, ConverterParameter=Unitaire}" GroupName="envSource" Width="79" Content="Unitaire" HorizontalAlignment="Left" Margin="4,160,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="rdbFonctionnel" IsChecked="{Binding Path=EnvironnementSource, Mode=TwoWay, ConverterParameter=Fonctionnel}" Content="Fonctionnel" GroupName="envSource" Width="79" HorizontalAlignment="Left" Margin="4,183,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="rdbIntegre" IsChecked="{Binding Path=EnvironnementSource, Mode=TwoWay, ConverterParameter=Integre}" GroupName="envSource" Width="79" Content="Intégré" HorizontalAlignment="Left" Margin="4,206,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="rdbAcceptation" IsChecked="{Binding Path=EnvironnementSource, Mode=TwoWay, ConverterParameter=Acceptation}" GroupName="envSource" Width="90" Content="Acceptation" HorizontalAlignment="Left" Margin="114,162,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="rdbFormation" IsChecked="{Binding Path=EnvironnementSource, Mode=TwoWay, ConverterParameter=Formation}" GroupName="envSource" Width="90" Content="Formation" HorizontalAlignment="Left" Margin="114,183,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="rdbProduction" IsChecked="{Binding Path=EnvironnementSource, Mode=TwoWay, ConverterParameter=Production}" GroupName="envSource" Width="90" Content="Production" HorizontalAlignment="Left" Margin="114,206,0,0" VerticalAlignment="Top"/>
<Button x:Name="Login" Content="Connexion" HorizontalAlignment="Left" Margin="4,252,0,0" VerticalAlignment="Top" Width="200" Command="{Binding ButtonCommand}"/>
</Grid>
</GroupBox>
<!--<Rectangle Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="317" VerticalAlignment="Top" Width="220" RadiusY="5" RadiusX="5" Stroke="Black" Opacity="0.1" Margin="0,350,0,-179"/>-->
<GroupBox Width="220" Header="Environnement source" Margin="6,338,17,57" IsEnabled="False" Background="{DynamicResource {x:Static SystemColors.ScrollBarBrushKey}}">
<Grid Margin="0,0,0,20">
<Label x:Name="lblIdentifiantCopie" Content="Identifiant de l'utilisateur :" HorizontalAlignment="Left" Margin="4,24,0,0" VerticalAlignment="Top" Width="200"/>
<TextBox x:Name="txtNomUsagerCopie" HorizontalAlignment="Left" Height="23" Margin="4,47,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="200"/>
<Label x:Name="lblMotDePasseCopie" Content="Mot de passe :" HorizontalAlignment="Left" Margin="4,80,0,0" VerticalAlignment="Top" Width="200"/>
<PasswordBox x:Name="txtMotDePasseCopie" HorizontalAlignment="Left" Height="23" Margin="4,103,0,0" VerticalAlignment="Top" Width="200"/>
<RadioButton x:Name="rdbUnitCopie" Width="79" Content="Unitaire" HorizontalAlignment="Left" Margin="4,160,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="rdbFonctionnelCopie" Width="79" Content="Fonctionnel" HorizontalAlignment="Left" Margin="4,183,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="rdbIntegreCopie" Width="79" Content="Intégré" HorizontalAlignment="Left" Margin="4,206,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="rdbAcceptationCopie" Width="90" Content="Acceptation" HorizontalAlignment="Left" Margin="114,162,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="rdbFormationCopie" Width="90" Content="Formation" HorizontalAlignment="Left" Margin="114,183,0,0" VerticalAlignment="Top"/>
<RadioButton x:Name="rdbProductionCopie" Width="90" Content="Production" HorizontalAlignment="Left" Margin="114,206,0,0" VerticalAlignment="Top"/>
<Button x:Name="btnAjout" Content="Ajouter dans l'environnement" HorizontalAlignment="Left" Margin="4,252,0,0" VerticalAlignment="Top" Width="200"/>
</Grid>
</GroupBox>
</Grid>
</UserControl>
MigrationModeleView.xaml
<UserControl x:Class="MvvmLight1.MigrationModeleView"
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:MvvmLight1"
mc:Ignorable="d" d:DesignWidth="630" Height="587"
DataContext="{Binding Main, Source={StaticResource Locator}}">
<Grid Margin="15,22,0,0">
<GroupBox Header="Migration de modèle de lettre" Margin="6,10,0,32">
<Grid Margin="0,0,0,4">
<Label x:Name="lblChoixPPP" Content="PPP :" HorizontalAlignment="Left" Margin="19,13,0,0" VerticalAlignment="Top"/>
<ComboBox x:Name="cbxChoixPPP" HorizontalAlignment="Left" Margin="67,13,0,0" VerticalAlignment="Top" Width="120"/>
<DataGrid x:Name="dgModeles" HorizontalAlignment="Left" Margin="19,61,0,0" VerticalAlignment="Top" Height="162" Width="565">
<DataGrid.Columns>
<DataGridCheckBoxColumn Header=""/>
<DataGridTextColumn Header="Numéro de référence" Width="150" />
<!--Binding="{Binding Nom}"-->
<DataGridTextColumn Header="Titre du modèle de lettre" />
<!--Binding="{Binding Prenom}"-->
</DataGrid.Columns>
</DataGrid>
<Label x:Name="lblRechercher" Content="Rechercher :" HorizontalAlignment="Left" Margin="19,239,0,0" VerticalAlignment="Top"/>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="91,241,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="291"/>
<Button x:Name="btnAfficherTout" Content="Afficher tout" HorizontalAlignment="Left" Margin="387,244,0,0" VerticalAlignment="Top" Width="96"/>
<Button x:Name="btnAfficherSelection" IsEnabled="False" Content="Afficher sélection" HorizontalAlignment="Left" Margin="488,244,0,0" VerticalAlignment="Top" Width="96"/>
<DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Margin="19,319,0,0" VerticalAlignment="Top" Height="162" Width="565">
<DataGrid.Columns>
<DataGridTextColumn Header="Résultat de la copie" Width="150" />
<DataGridTextColumn Header="" />
</DataGrid.Columns>
</DataGrid>
<ProgressBar HorizontalAlignment="Left" Height="20" Margin="22,509,0,-26" VerticalAlignment="Top" Width="464"/>
<Button x:Name="btnDetails" Height="20" IsEnabled="False" Content="Détails" HorizontalAlignment="Left" Margin="491,509,0,-26" VerticalAlignment="Top" Width="96"/>
</Grid>
</GroupBox>
</Grid>
</UserControl>
MainViewModel.cs
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
namespace MvvmLight1.ViewModel
{
/// <summary>
/// This class contains properties that the main View can data bind to.
/// <para>
/// See http://www.mvvmlight.net
/// </para>
/// </summary>
public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
}
public RelayCommand ButtonCommand
{
get { return new RelayCommand(() => { EnabledView = !EnabledView; }); }
}
private bool _environmentSource;
public bool EnvironnementSource
{
get { return _environmentSource; }
set { Set(ref _environmentSource, value); }
}
private string _idUtilisateur;
public string IdUtilisateur
{
get { return _idUtilisateur; }
set { Set(ref _idUtilisateur, value); }
}
private bool _enabledView;
public bool EnabledView
{
get { return _enabledView; }
set { Set(ref _enabledView, value); }
}
}
}
ViewModelLocator.cs
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Ioc;
using Microsoft.Practices.ServiceLocation;
namespace MvvmLight1.ViewModel
{
/// <summary>
/// This class contains static references to all the view models in the
/// application and provides an entry point for the bindings.
/// <para>
/// See http://www.mvvmlight.net
/// </para>
/// </summary>
public class ViewModelLocator
{
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<MainViewModel>();
}
/// <summary>
/// Gets the Main property.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "This non-static member is needed for data binding purposes.")]
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
/// <summary>
/// Cleans up all the resources.
/// </summary>
public static void Cleanup()
{
}
}
}

Categories

Resources