Getting the parent of usercontrol inside Dispatcher.BeginInvoke - c#

Am having a Main window in my WPF application inside which am having a tabcontrol.I need to select the tabitem based on the name i pass.Each of the tabitem will contain a user control.But my problem is am not able to get the parent of the usercontrol using Parent property.Its returning null only always.Can anyone help me out.
public void selectingTab()
{
Dispatcher.BeginInvoke((Action)(() =>
{
string name = todisplayChat.GetValue<string>("FromMessenger");
string msg = todisplayChat.GetValue<string>("ChatSent");
NewChatWindow childWindow = this as NewChatWindow;
MainChatWindow parentWindow = VisualTreeHelper.GetParent(childWindow) as MainChatWindow;
//Am getting null as the value of parentWindow after the execution of this line
TabControl tabcontrolHome = parentWindow.tabcontrol_Chatwindow;
TabItem existingTab = tabcontrolHome.Items.OfType<TabItem>().SingleOrDefault(n => n.Name == name);
childWindow = (NewChatWindow)existingTab.Content;
childWindow.richtxtbox_chatwindow.AppendText(Environment.NewLine + name + " : " + msg);
}));
}
MainChatWindow.XAML
<Window x:Class="Ping.MainChatWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="600" Width="700" Icon="F:\Dhivya\C#\Personal\ChatApplication\CurrentlyWorking-Important\Ping\Ping\images\ping_logo.png" ResizeMode="CanMinimize" WindowStartupLocation="CenterScreen" WindowStyle="None" Foreground="{x:Null}" BorderBrush="#FF87A4DB" BorderThickness="2">
<Grid>
<Label Content="Ping" Height="30" HorizontalAlignment="Left" Name="lbl_Titlebar" VerticalAlignment="Top" Width="700" Background="#FF87A4DB" FontFamily="Arial" FontSize="17" Foreground="White" />
<Image Height="20" HorizontalAlignment="Left" Margin="635,5,0,0" Name="img_Minimizebutton" Stretch="Fill" VerticalAlignment="Top" Width="20" Source="F:\Dhivya\C#\Personal\ChatApplication\CurrentlyWorking-Important\Ping\Ping\images\minimize_userpage.png" />
<!--<Label Height="25" HorizontalAlignment="Left" Margin="665,5,0,0" VerticalAlignment="Top" Width="20">-->
<Image MouseEnter="close_icon_MouseEnter_1" MouseDown="close_icon_MouseDown_1" Height="20" HorizontalAlignment="Left" Margin="665,5,0,0" Name="close_icon" Stretch="Fill" VerticalAlignment="Top" Width="20" Source="F:\Dhivya\C#\Personal\ChatApplication\CurrentlyWorking-Important\Ping\Ping\images\close_userpage.png" />
<!--</Label>-->
<Label Content="Groups" Height="28" HorizontalAlignment="Left" Margin="12,46,0,0" Name="lbl_Groups" VerticalAlignment="Top" Background="#FF87A4DB" Foreground="White" BorderBrush="{x:Null}" Width="245" FontSize="16" FontFamily="Arial" />
<RichTextBox ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" Height="175" HorizontalAlignment="Left" Margin="12,73,0,0" Name="richtxtbox_Groups" VerticalAlignment="Top" Width="245" FontFamily="Arial" />
<Label Background="#FF87A4DB" BorderBrush="{x:Null}" Content="Online Buddies" FontFamily="Arial" FontSize="16" Foreground="White" Height="28" HorizontalAlignment="Left" Margin="12,260,0,0" Name="lbl_Onlinebuddies" VerticalAlignment="Top" Width="245" />
<Grid ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" Height="298" HorizontalAlignment="Left" Margin="12,288,0,0" Name="richtxtbox_Onlinebuddies" VerticalAlignment="Top" Width="245"></Grid>
<!--<RichTextBox ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" Height="298" HorizontalAlignment="Left" Margin="12,288,0,0" Name="richtxtbox_Onlinebuddies" VerticalAlignment="Top" Width="245" FontFamily="Arial" />-->
<TabControl Height="540" HorizontalAlignment="Left" Margin="274,46,0,0" Name="tabcontrol_Chatwindow" VerticalAlignment="Top" Width="410">
<TabItem Header="My Profile" Name="ProfileTab">
</TabItem>
</TabControl>
</Grid>
NewChatWindow.Xaml
<UserControl x:Class="Ping.NewChatWindow"
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="540" d:DesignWidth="410">
<Grid>
<TextBox LostFocus="txt_Userinput_LostFocus_1" Foreground="Gray" GotFocus="txt_Userinput_GotFocus_1" KeyDown="txt_Userinput_KeyDown_1" Height="65" HorizontalAlignment="Left" Margin="13,161,0,0" Name="txt_Userinput" VerticalAlignment="Top" Width="378" FontFamily="Arial" Text="Enter Your Words Here" />
<RichTextBox ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" Height="246" HorizontalAlignment="Left" Margin="13,253,0,0" Name="richtxtbox_chatwindow" VerticalAlignment="Top" Width="378" FontFamily="Arial" />
<Image Height="93" HorizontalAlignment="Left" Margin="36,36,0,0" Name="image2" Stretch="Fill" VerticalAlignment="Top" Width="65" Source="F:\Dhivya\C#\Personal\ChatApplication\CurrentlyWorking-Important\Ping\Ping\images\user_logo.png"/>
<Label Content="Label" Height="37" HorizontalAlignment="Left" Margin="124,24,0,0" Name="lbl_Username" VerticalAlignment="Top" Width="278" FontSize="24" />
<Label Content="Label" Height="28" HorizontalAlignment="Left" Margin="125,52,0,0" Name="lbl_Statusmsg" VerticalAlignment="Top" Width="284" />
<Image Height="40" Width="30" HorizontalAlignment="Left" Margin="131,89,0,0" Name="img_Profileview" Stretch="Fill" VerticalAlignment="Top" Source="F:\Dhivya\C#\Personal\ChatApplication\CurrentlyWorking-Important\Ping\Ping\images\user_logo.png" ToolTip="Add contact"/>
<Image MouseDown="img_Sendingfile_MouseDown_1" Height="40" Width="40" HorizontalAlignment="Left" Margin="191,89,0,0" Name="img_Sendingfile" Stretch="Fill" VerticalAlignment="Top" Source="F:\Dhivya\C#\Personal\ChatApplication\CurrentlyWorking-Important\Ping\Ping\images\sendingfile_icon.png" ToolTip="Fileupload"/>
<Image Height="40" Width="40" HorizontalAlignment="Left" Margin="261,89,0,0" Name="img_Videochat" Stretch="Fill" VerticalAlignment="Top" Source="F:\Dhivya\C#\Personal\ChatApplication\CurrentlyWorking-Important\Ping\Ping\images\videochat_logo.png" ToolTip="Video chat"/>
<Image MouseDown="img_Myfolder_MouseDown_1" Height="40" Width="40" Name="img_Myfolder" Stretch="Fill" Source="F:\Dhivya\C#\Personal\ChatApplication\CurrentlyWorking-Important\Ping\Ping\images\myfolder_logo.png" Margin="329,89,41,411" ToolTip="View chat history" />
<Border BorderBrush="#FF87A4DB" BorderThickness="1" HorizontalAlignment="Left" Margin="10,18,0,367" Name="border_Userdetails" Width="378" CornerRadius="2" />
</Grid>
Am having a set of labels for the online users.So when i double click any label i ll do the following
private void Label_MouseDoubleClick_1(object sender, MouseButtonEventArgs e)
{
Label selectedLabel = (Label)sender;
TabItem existingTab = tabcontrol_Chatwindow.Items.OfType<TabItem>().SingleOrDefault(n => n.Name == selectedLabel.Content);
if (tabcontrol_Chatwindow.Items.Contains(existingTab))
{
tabcontrol_Chatwindow.SelectedItem = existingTab;
}
else
{
TabItem newTab = new TabItem();
newTab.Name = selectedLabel.Content.ToString();
TabHeader header = new TabHeader();
header.userName.Content = selectedLabel.Content;
newTab.Header = header;
//newTab.Header = selectedLabel.Content;
newTab.Content = new NewChatWindow();
tabcontrol_Chatwindow.Items.Add(newTab);
tabcontrol_Chatwindow.SelectedItem = newTab;
}
}

Try using the below code, in which you can find the Window hosting your Usercontrol using Window parentWindow = Window.GetWindow(this);
Dispatcher.BeginInvoke((Action)(() =>
{
string name = todisplayChat.GetValue<string>("FromMessenger");
string msg = todisplayChat.GetValue<string>("ChatSent");
NewChatWindow childWindow = this as NewChatWindow;
MainChatWindow parentWindow = Window.GetWindow(this) as MainChatWindow;
TabControl tabcontrolHome = parentWindow.tabcontrol_Chatwindow;
TabItem existingTab = tabcontrolHome.Items.OfType<TabItem>().SingleOrDefault(n => n.Name == name);
childWindow = (NewChatWindow)existingTab.Content;
childWindow.richtxtbox_chatwindow.AppendText(Environment.NewLine + name + " : " + msg);
}));

Related

WPF Buttons: How to fix double clicking to trigger click event

I have a WPF layout that consists of several buttons in a toolbar. When the "New Item" button is clicked, another row of text boxes is created. However, the delete button has to be clicked on two times in order for the last created row to be deleted. How would I make the click event for the "Delete" work for a single click and not a double click?
Here is the XMAL code:
<Window x:Class="Odan_Estimator_Tool.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:Odan_Estimator_Tool"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<Grid ScrollViewer.CanContentScroll="True" Name="GridMain">
<DockPanel>
<ToolBarTray DockPanel.Dock="Top">
<ToolBar Height="40" Margin="0,0,-1,0">
<Button Content="New Item" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" RenderTransformOrigin="-0.512,0.521" Height="19" Click="NewItem" Margin="0,10,0,0"/>
<Button Content="Delete" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="19" Margin="0,10,0,0" Click="DeleteItem"/>
<Button Content="Calculate" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" RenderTransformOrigin="-0.203,0.604" Height="19" Margin="0,9,0,0" />
</ToolBar>
</ToolBarTray>
</DockPanel>
<TextBox HorizontalAlignment="Left" Height="23" Margin="10,76,0,0" TextWrapping="Wrap" Text="{Binding Id, Mode=TwoWay}" VerticalAlignment="Top" Width="145"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="606,76,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="176"/>
<Label Content="Item #" HorizontalAlignment="Left" Margin="10,45,0,0" VerticalAlignment="Top" Height="26" Width="145"/>
<Label Content="Description" HorizontalAlignment="Left" Margin="262,45,0,0" VerticalAlignment="Top" Height="26" Width="226"/>
<Label Content="Unit" HorizontalAlignment="Left" Margin="160,45,0,0" VerticalAlignment="Top" RenderTransformOrigin="-1.725,-4.203" Height="26" Width="102"/>
<Label Content="Type" HorizontalAlignment="Left" Margin="493,45,0,0" VerticalAlignment="Top" RenderTransformOrigin="2.705,2.641" Height="26" Width="113"/>
<Label Content="Est. Qty" HorizontalAlignment="Left" Margin="611,45,0,0" VerticalAlignment="Top" RenderTransformOrigin="4.5,1.203" Height="26" Width="158"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="259,76,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="229" />
<TextBox HorizontalAlignment="Left" Height="23" Margin="155,76,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="104" />
<TextBox HorizontalAlignment="Left" Height="23" Margin="488,76,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="118" RenderTransformOrigin="1.403,0.47"/>
<ScrollViewer HorizontalAlignment="Left" Height="245" Margin="914,154,-506,0" VerticalAlignment="Top" Width="384"/>
<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="45" VerticalAlignment="Top" Width="792"/>
</Grid>
</ScrollViewer>
Here is the C# code with the Delete function at the bottom.
private void NewItem(object sender, RoutedEventArgs e)
{
//Generates new row of text boxes
//Generates new item ID textbox
TextBox item_box = new TextBox();
item_box.Height = 23;
item_box.Width = 161;
item_box.Text = "";
item_box.Margin = new Thickness(21, 76 + 23*counter, 0, 0);
item_box.VerticalAlignment = 0;
item_box.HorizontalAlignment = 0;
items.Add(item_box);
GridMain.Children.Add(item_box);
//Generates new item ID textbox
TextBox id_box = new TextBox();
id_box.Height = 23;
id_box.Width = 161;
id_box.Text = "";
id_box.Margin = new Thickness(21, 76 + 23 * counter, 0, 0);
id_box.VerticalAlignment = 0;
id_box.HorizontalAlignment = 0;
items.Add(id_box);
GridMain.Children.Add(id_box);
counter++;
}
private void DeleteItem(object sender, RoutedEventArgs e)
{
GridMain.Children.Remove(items.ElementAt(items.Count - 1));
items.RemoveAt(items.Count - 1);
}

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()
{
}
}
}

textbox text not becoming empty on button command

I have a button with binding as ClearCommand which clears the value of text box but it is not working.
public SellerDetailsViewModel() //constructor
{
sdObject = new SellerDetailsTable();
_SaveCommand = new RelayCommand(Save, CanSave);
_ClearCommand = new RelayCommand(clear, Canclear);
}
private readonly ICommand _ClearCommand;
public ICommand ClearCommand { get { return _ClearCommand; } }
public event PropertyChangedEventHandler PropertyChanged;
public void onPropertyChange(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public bool Canclear(object obj)
{
return true;
}
public void clear(object obj)
{
this.PancardNumber = "";
this.ContactNumber = 0;
this.FirstName = "";
this.LastName = "";
this.MiddleName = "";
this.OtherDocument = "";
this.Address = "";
}
<Page x:Class="CarDealer.SellerDetails"
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="800" d:DesignWidth="900"
xmlns:ViewModels="clr-namespace:CarDealer.PresentationLayer.ViewModel"
Title="SellerDetails">
<Page.Resources>
<ViewModels:SellerDetailsViewModel x:Key="ViewModel">
</ViewModels:SellerDetailsViewModel>
<ControlTemplate x:Key="TextBoxErrorTemplate">
<DockPanel LastChildFill="True">
<TextBlock DockPanel.Dock="Bottom" Foreground="Red" FontSize="10pt"
Text="{Binding ElementName=MyAdorner,Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"/>
<Border BorderBrush="Red" BorderThickness="2" Width="225" Height="35" >
<AdornedElementPlaceholder Name="MyAdorner" />
</Border>
</DockPanel>
</ControlTemplate>
</Page.Resources>
<Grid DataContext="{Binding Source={StaticResource ViewModel}}">
<Label Content="Seller Details" Height="39" HorizontalAlignment="Left" Margin="27,25,0,0" Name="lblTitle" VerticalAlignment="Top" FontSize="22" FontWeight="Bold" FontFamily="Times New Roman" Foreground="#FF1313D8" Width="169" />
<Label Content="First Name" Height="28" HorizontalAlignment="Left" Margin="44,87,0,0" Name="lblCustName" VerticalAlignment="Top" FontSize="16" />
<Label Content="Address" FontSize="16" Height="28" HorizontalAlignment="Left" Margin="461,253,0,0" Name="lblAdress" VerticalAlignment="Top" />
<Label Content="Pan Card Number" FontSize="16" Height="28" HorizontalAlignment="Left" Margin="44,243,0,0" Name="lblPanCardNumber" VerticalAlignment="Top" />
<Label Content="Contact Number" FontSize="16" Height="28" HorizontalAlignment="Left" Margin="44,320,0,0" Name="lblContactNumber" VerticalAlignment="Top" />
<Label Content="Handover Date" FontSize="16" Height="28" HorizontalAlignment="Left" Margin="461,170,0,0" Name="label1" VerticalAlignment="Top" />
<Label Content="Other Document" FontSize="16" Height="28" HorizontalAlignment="Left" Margin="44,399,0,0" Name="label2" VerticalAlignment="Top" />
<Button Content="Save" Height="37" Command="{Binding SaveCommand}" HorizontalAlignment="Left" Margin="299,543,0,0" Name="btnSave" VerticalAlignment="Top" Width="131" FontSize="22" />
<TextBox Height="33" Text="{Binding FirstName, Mode=TwoWay}" HorizontalAlignment="Left" Margin="205,92,0,0" Name="txtFirstName" VerticalAlignment="Top" Width="225" BorderThickness="2" FontSize="16" />
<Label Content="Last Name" FontSize="16" Height="28" HorizontalAlignment="Left" Margin="44,165,0,0" Name="label3" VerticalAlignment="Top" />
<TextBox BorderThickness="2" Text="{Binding LastName, Mode=TwoWay}" Height="33" HorizontalAlignment="Left" Margin="205,170,0,0" Name="txtLastName" VerticalAlignment="Top" Width="225" FontSize="16" />
<TextBox BorderThickness="2" Text="{Binding PancardNumber, Mode=TwoWay}" Height="33" HorizontalAlignment="Left" Margin="205,248,0,0" Name="txtPanCard" VerticalAlignment="Top" Width="225" FontSize="16" />
<TextBox BorderThickness="2" Height="33" HorizontalAlignment="Left" Margin="205,325,0,0" Validation.ErrorTemplate="{StaticResource TextBoxErrorTemplate}" Name="txtcontactNumber" VerticalAlignment="Top" Width="225" FontSize="16">
<TextBox.Text>
<Binding Path="ContactNumber">
<Binding.ValidationRules>
<ExceptionValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<TextBox Height="126" Text="{Binding Address, Mode=TwoWay}" HorizontalAlignment="Left" Margin="627,248,0,0" Name="TxtAddress" VerticalAlignment="Top" Width="257" BorderThickness="2" FontSize="16" VerticalScrollBarVisibility="Visible" />
<TextBox BorderThickness="2" Text="{Binding OtherDocument, Mode=TwoWay}" Height="126" HorizontalAlignment="Left" Margin="205,399,0,0" Name="rchTxtOtherDoc" VerticalAlignment="Top" Width="257" FontSize="16" VerticalScrollBarVisibility="Visible" />
<DatePicker Height="33" Text="{Binding HandoverDate}" HorizontalAlignment="Left" Margin="627,170,0,0" Name="dtPickerHandoverDate" VerticalAlignment="Top" Width="225" FontSize="16" />
<Button Content="Clear All" Command="{Binding ClearCommand}" FontSize="22" Height="37" HorizontalAlignment="Left" Margin="500,543,0,0" Name="btnClearAll" VerticalAlignment="Top" Width="131" />
<Label Content="Middle Name" FontSize="16" Height="28" HorizontalAlignment="Left" Margin="471,87,0,0" Name="label4" VerticalAlignment="Top" />
<TextBox BorderThickness="2" Text="{Binding MiddleName, Mode=TwoWay}" FontSize="16" Height="33" HorizontalAlignment="Left" Margin="627,87,0,0" Name="txtMiddleName" VerticalAlignment="Top" Width="225" />
</Grid>
I have debugged the code execution. clear function is executed but in the view, the textbox is not empty. Can you help me figure out what I am doing wrong?
I have added remaining code please what is missing.
You should post the rest of your xaml. Assuming your controls are TextBox's...
public void clear(object obj)
{
this.PancardNumber.Text = "";
this.ContactNumber.Text = "0"; //depends what this control is
this.FirstName.Text = "";
this.LastName.Text = "";
this.MiddleName.Text = "";
this.OtherDocument.Text = "";
this.Address.Text = "";
}
Try this, hope it helps.
public void clear(object obj)
{
this.PancardNumber = "";
this.ContactNumber = 0;
this.FirstName = "";
this.LastName = "";
this.MiddleName = "";
this.OtherDocument = "";
this.Address = "";
// should work on other document
OnPropertyChanged("OtherDocument");
}
<Button Content="Clear All" Command="{Binding ClearCommand}" FontSize="22" Height="37" HorizontalAlignment="Left" Margin="500,543,0,0" Name="btnClearAll" VerticalAlignment="Top" Width="131" />
<TextBox BorderThickness="2" Text="{Binding OtherDocument, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Height="126" HorizontalAlignment="Left" Margin="205,399,0,0" Name="rchTxtOtherDoc" VerticalAlignment="Top" Width="257" FontSize="16" VerticalScrollBarVisibility="Visible" />

Drop event not firing for canvas/StackPanel in Silverlight

XAML
<Grid x:Name="LayoutRoot" Background="White">
<Canvas x:Name="VideoCanvas" Width="800" Height="600" AllowDrop="True" Background="RosyBrown" HorizontalAlignment="Center">
<StackPanel Drop="VideoCanvas_Drop" AllowDrop="True" Name="CommandBar" Orientation="Horizontal" Background="Beige" Height="39" Width="783" Margin="5" HorizontalAlignment="Center" Canvas.Left="3">
<Button Name="PlayMovie" Background="AntiqueWhite" Content="Play" FontWeight="Bold" Click="PlayMovie_Click" Margin="50,5,0,5" Width="100"/>
<Button Name="PauseMovie" Background="AntiqueWhite" Content="Pause" FontWeight="Bold" Click="PauseMovie_Click" Margin="50,5,0,5" Width="100"/>
<Button Name="VideoStop" Background="AntiqueWhite" Content="Stop" FontWeight="Bold" Click="VideoStop_Click" Margin="50,5,0,5" Width="100" />
</StackPanel>
<MediaElement x:Name="mediaEl" Canvas.Top="150" Width="800" Height="450" AllowDrop="True" AutoPlay="True" />
</Canvas>
</Grid>
C#
private void VideoCanvas_Drop(object sender, DragEventArgs e)
{
DragEventArgs dr = e as DragEventArgs;
if (dr.Data == null)
return;
IDataObject data = dr.Data;
FileInfo[] file = data.GetData(DataFormats.FileDrop) as FileInfo[];
if (file.Count() > 0)
mediaEl.SetSource(file[0].OpenRead());
if (mediaEl.CurrentState != MediaElementState.Playing)
{
mediaEl.Play();
}
}
Drag and Drop is not implemented by default in Silverlight. To use Drag & Drop functionality in Silverlight you have to use the DragDropTargets (PanelDragDropTarget, ListBoxDragDropTarget,...) from Silverlight Toolkit.
XAML
<Grid x:Name="LayoutRoot" Background="White">
<Canvas x:Name="VideoCanvas" Width="800" Height="600" AllowDrop="True" Background="RosyBrown" HorizontalAlignment="Center">
<toolkit:PanelDragDropTarget AllowDrop="True" Drop="VideoCanvas_Drop">
<StackPanel Name="CommandBar" Orientation="Horizontal" Background="Beige" Height="39" Width="783" Margin="5" HorizontalAlignment="Center" Canvas.Left="3">
<Button Name="PlayMovie" Background="AntiqueWhite" Content="Play" FontWeight="Bold" Click="PlayMovie_Click" Margin="50,5,0,5" Width="100"/>
<Button Name="PauseMovie" Background="AntiqueWhite" Content="Pause" FontWeight="Bold" Click="PauseMovie_Click" Margin="50,5,0,5" Width="100"/>
<Button Name="VideoStop" Background="AntiqueWhite" Content="Stop" FontWeight="Bold" Click="VideoStop_Click" Margin="50,5,0,5" Width="100" />
</StackPanel>
</toolkit:PanelDragDropTarget>
<MediaElement x:Name="mediaEl" Canvas.Top="150" Width="800" Height="450" AllowDrop="True" AutoPlay="True" />
</Canvas>
</Grid>
C#
private void VideoCanvas_Drop(object sender, Microsoft.Windows.DragEventArgs e)
{
DragEventArgs dr = e as DragEventArgs;
if (dr.Data == null)
return;
IDataObject data = dr.Data;
FileInfo[] file = data.GetData(DataFormats.FileDrop) as FileInfo[];
if (file.Count() > 0)
mediaEl.SetSource(file[0].OpenRead());
if (mediaEl.CurrentState != MediaElementState.Playing)
{
mediaEl.Play();
}
}

Categories

Resources