Is ApplicationSettings working properly on emulator? - c#

I have this simple xaml page to collect user information:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBlock Height="50" HorizontalAlignment="Left" Margin="6,36,0,0" Text="Enter your birth year :" VerticalAlignment="Top" Width="312" FontSize="32" />
<TextBox FontSize="32" Height="84" HorizontalAlignment="Left" Margin="310,19,0,0" Name="birthyear" Text="" VerticalAlignment="Top" Width="146" TextAlignment="Center" />
<TextBlock Height="60" HorizontalAlignment="Left" Margin="12,112,0,0" Name="birthyear_message" Text="" VerticalAlignment="Top" Width="438" />
<TextBlock FontSize="32" Height="50" HorizontalAlignment="Left" Margin="6,283,0,0" Text="Enter your post code :" VerticalAlignment="Top" Width="312" />
<TextBox FontSize="32" TextAlignment="Center" Height="82" HorizontalAlignment="Left" Margin="310,268,0,0" Name="postcode" Text="" VerticalAlignment="Top" Width="146" />
<TextBlock Height="60" HorizontalAlignment="Left" Margin="12,356,0,0" Name="postcode_message" Text="" VerticalAlignment="Top" Width="438" />
<Button Content="Cancel" Height="72" HorizontalAlignment="Left" Margin="31,441,0,0" Name="cancel" VerticalAlignment="Top" Width="160" Click="cancel_Click" />
<Button Content="Save" Height="72" HorizontalAlignment="Left" Margin="247,441,0,0" Name="save" VerticalAlignment="Top" Width="160" Click="save_Click" />
</Grid>
My code behind is like this:
//Set and display user a set of default values if user is accessing page for first time else retrieve data from the settings
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
var settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains("birthyear"))
birthyear.Text = settings["birthyear"].ToString();
else
{
birthyear.Text = (DateTime.Now.Year - 25).ToString();
settings.Add("birthyear", birthyear.Text);
}
if (settings.Contains("postcode"))
birthyear.Text = settings["postcode"].ToString();
else
{
postcode.Text = "10044";
settings.Add("postcode", postcode.Text);
}
}
private void save_Click(object sender, RoutedEventArgs e)
{
var settings = IsolatedStorageSettings.ApplicationSettings;
//ignore error conditions for the time being!
settings.Remove("birthyear");
settings.Add("birthyear", birthyear.Text);
settings.Remove("postcode");
settings.Add("postcode", postcode.Text);
settings.Save();
//Navigate to the same page to validate values entered by user is saved
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
Now coming to the problem. When the user navigates for the first time, the default values of 1986 and 10044 are shown. Now I edit the values, say 1999 and 65222 and select Save. What happens now is that the birthyear is showing 65222 and postcode is showing blank. What is the problem?
Update:
When I try to retrieve the values in the Intermediate Window in VS, the new values are displayed properly. I am guessing it is saving properly but is having problems while retrieving/displaying it

You could try changeing the value instead, and do
settings["birthyear"] = birthyear.Text;
settings["postcode"] = postcode.Text;
And maybe also try casting your settings as type IsolatedStorageSettings.
EDIT:
settings.Remove("birthyear");
settings.Add("birthyear", birthyear.Text);
settings.Remove("postcode");
settings.Add("postcode", postcode.Text);
settings.Save();
Becomes:
settings["birthyear"] = birthyear.Text;
settings["postcode"] = postcode.Text;

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);
}

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.

How to check if any radiobutton is checked

I have 4 radiobuttons and I want to check if any are checked.
This is my WPF code:
<StackPanel Background="#FF3A3A49" Grid.Column="1" Grid.Row="4">
<RadioButton x:Name="rtnRight" GroupName="answer" HorizontalAlignment="Center" VerticalAlignment="Top" Foreground="White" Content="value0" BorderBrush="White"/>
<RadioButton Content="value1" GroupName="answer" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" />
<RadioButton Content="value2" GroupName="answer" HorizontalAlignment="Center" VerticalAlignment="Bottom" Foreground="White" />
<RadioButton Content="value3" GroupName="answer" HorizontalAlignment="Center" VerticalAlignment="Bottom" Foreground="White" />
</StackPanel>
<Button x:Name="btnNext" Grid.Column="1" Grid.Row="5" Content="Dalej" VerticalAlignment="Center" HorizontalAlignment="Center" Width="100" Height="50" Margin="0 0 0 0 " Foreground="#FFAC0303" BorderBrush="#FFC1C1C1" Background="#66FFFFFF" Click="btnNext_Click"></Button>
After I click btnNext and no radiobuttons have been checked, I want to show a message dialog. How can I code this? This is my btnNext_Click function so far.
private async void btnNext_Click(object sender, RoutedEventArgs e)
{
if ("any radiobutton checked?")
{
await new Windows.UI.Popups.MessageDialog("Choose at least one answer").ShowAsync();
}
}
You can specify a name for your StackPanel and then check like:
if (!(radioButtonStackPanel.Children.OfType<RadioButton>().Any(rb => rb.IsChecked == true)))
Just remember to specify a name for StackPanel like:
<StackPanel Background="#FF3A3A49" Grid.Column="1" Grid.Row="4" x:Name="radioButtonStackPanel">

how to reset the value of a radio button in windows phone 7 application using c#

I have a form in my windows phone 7 app which contains a few textboxes and a radiobutton. I want to reset the value of the textboxes and radio button on clicking the reset button. I am able to clear the textboxes but donot Know how to clear the value of the radio button. Please help:
My form is:
<TextBox GotFocus="OnGotFocus" Canvas.Left="6" Canvas.Top="6" Height="74" Name="name" Text="*Name" Width="453" BorderThickness="0"/>
<TextBox GotFocus="OnGotFocus1" Canvas.Left="6" Canvas.Top="66" Height="74" Name="age" Text="*Age" Width="453" BorderThickness="0" />
<TextBlock Canvas.Left="20" Canvas.Top="157" Height="44" Name="gen" Text="Gender" Foreground="Black" FontFamily="Verdana" FontSize="24" Width="134" />
<RadioButton Canvas.Left="139" Canvas.Top="157" FontStyle="Italic" Foreground="Black" Content="Male" Height="71" Name="male" Width="154" />
<RadioButton Canvas.Left="139" Canvas.Top="207" FontStyle="Italic" Foreground="Black" Content="Female" Height="71" Name="fem" Width="140" />
<TextBox GotFocus="OnGotFocus2" Canvas.Left="6" Canvas.Top="267" Height="74" Name="sadd" Text="*Street Address" Width="453" BorderThickness="0"/>
<TextBox GotFocus="OnGotFocus3" Canvas.Left="6" Canvas.Top="327" Height="74" Name="cadd" Text="*City Address" Width="453" BorderThickness="0"/>
<TextBox GotFocus="OnGotFocus4" Canvas.Left="6" Canvas.Top="387" Height="74" Name="eadd" Text="*Email Address" Width="453" BorderThickness="0"/>
<TextBox GotFocus="OnGotFocus5" Canvas.Left="6" Canvas.Top="447" Height="74" Name="phn" Text="*Phone" Width="453" BorderThickness="0"/>
<TextBox GotFocus="OnGotFocus6" Canvas.Left="6" Canvas.Top="507" Height="74" Name="zip" Text="*Zip Code" Width="453" BorderThickness="0"/>
My code for resetting on clicking the reset button is:
private void reset_Click(object sender, RoutedEventArgs e)
{
name.Text = "";
age.Text = "";
sadd.Text = "";
cadd.Text = "";
eadd.Text = "";
phn.Text = "";
zip.Text = "";
}
Please add the code that i should add here to reset the radio button
Now on clicking submit button if i want to check that whether male or female has been selected or not, how can i do that. For text box i am doing the following code:
private void submit_Click(object sender, RoutedEventArgs e)
{
if (name.Text == "")
{
MessageBox.Show("Please Enter the name");
name.Focus();
}
}
There is a property named content which is equivalent to a textbox text property
And this is how you are gonna set it
male.IsChecked=false;
male.Content=String.Empty;
And regarding the edits.
assign a common groupname property to both the radiobuttons. ie
<RadioButton Canvas.Left="139" Canvas.Top="157" FontStyle="Italic" GroupName="Gender" Foreground="Black" Content="Male" Height="71" Name="male" Width="154" />
<RadioButton Canvas.Left="139" Canvas.Top="207" FontStyle="Italic" GroupName="Gender" Foreground="Black" Content="Female" Height="71" Name="fem" Width="140" />
This makes either of the two selected everytime in xaml.
Now getting the value of a radiobutton in code should be like.
if(male.IsChecked==true)
{
string gender=male.Content.ToString();
}
else if(female.isChecked==true)
{
string gender=female.Content.ToString();
}
else //none of them is selected.
{
MessageBox.Show("Text");
}

Close a Window programatically after a OK_Button click from a ViewModel using MVVM

I am showing a window. The instance is created and shown within the ViewModel (bad practice I know...)
NewWindow form = new NewWindow();
form.ShowDialog();
Within that form I have an OK_button which is doing stuff when it is pressed. There exist a ViewModel to this form which has the OK Command from the OK_Button.
After that button is pressed doing stuff I want to close that form programatically from within the viewmodel. How can I do that?
I use WPF
UPDATE
now lets see what I do wrong: Here the DataContext event is not fired although my Window with the ViewModel is shown!?
The window that is shown and must be closed from the ViewModel:
public partial class NewSchoolYearWindow : Window
{
public NewSchoolYearWindow()
{
InitializeComponent();
}
private void Window_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
NewSchoolYearViewModel vm = (NewSchoolYearViewModel)e.NewValue;
vm.CloseNewSchoolYearDialog += () => this.Close();
}
}
Why is the DataContextChanged even not fired?
I use this XAML in my Window:
<Window x:Class="TBM.View.NewSchoolYearWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ViewModel="clr-namespace:TBM.ViewModel"
Title="Start a new school year"
Height="412" Width="505"
WindowStartupLocation="CenterScreen"
WindowStyle="ThreeDBorderWindow"
ResizeMode="CanResize" DataContextChanged="Window_DataContextChanged">
<Window.Resources>
<ViewModel:NewSchoolYearViewModel x:Key="NewSchoolYearViewModelID" />
</Window.Resources>
<Grid DataContext="{Binding ., Source={StaticResource NewSchoolYearViewModelID}}" Name="MainGrid">
<TextBlock Height="27" HorizontalAlignment="Left" Margin="68,46,0,0" Name="textBlock1" Text="School year start" VerticalAlignment="Top" Width="98" />
<TextBlock Height="27" HorizontalAlignment="Left" Margin="68,93,0,0" Name="textBlock2" Text="School year end" VerticalAlignment="Top" Width="98" />
<TextBlock Height="27" HorizontalAlignment="Left" Margin="68,169,0,0" Name="textBlock4" Text="Database name:" VerticalAlignment="Top" Width="150" TextAlignment="Left" TextTrimming="CharacterEllipsis" />
<TextBlock Height="27" HorizontalAlignment="Left" Margin="68,215,0,0" Name="textBlock3" Text="Directory:" VerticalAlignment="Top" Width="63" TextAlignment="Left" TextTrimming="CharacterEllipsis" />
<TextBox IsReadOnly="True" Text="{Binding CurrentSchoolYear.Directory}" Height="23" HorizontalAlignment="Left" Margin="172,212,0,0" Name="textBox3" VerticalAlignment="Top" Width="224" />
<Button Command="{Binding OpenNewSchoolYearDialogCommand}" Content="DIR" Height="23" HorizontalAlignment="Right" Margin="0,211,27,0" Name="button1" VerticalAlignment="Top" Width="54" />
<Button Command="{Binding CreateNewSchoolYearCommand}" Content="OK" Height="23" HorizontalAlignment="Left" Margin="381,299,0,0" Name="button2" VerticalAlignment="Top" Width="75" />
<Button Content="Cancel" Height="23" HorizontalAlignment="Left" Margin="300,299,0,0" Name="button3" VerticalAlignment="Top" Width="75" />
<DatePicker Height="25" HorizontalAlignment="Left" Margin="172,42,0,0" SelectedDate="{Binding CurrentSchoolYear.Start}" SelectedDateFormat="Long" VerticalAlignment="Top" Width="175" />
<DatePicker Height="25" HorizontalAlignment="Left" Margin="172,89,0,0" SelectedDate="{Binding CurrentSchoolYear.End}" SelectedDateFormat="Long" VerticalAlignment="Top" Width="175" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="172,166,0,0" Name="textBox1" Text="{Binding CurrentSchoolYear.Name}" VerticalAlignment="Top" Width="175" />
</Grid>
</Window>
Declare an event in the ViewModel:
public event EventHandler<CloseRequestedEventArgs> CloseRequested;
protected virtual void OnCloseRequested(bool? dialogResult)
{
var handler = CloseRequested;
if (handler != null)
handler(this, new CloseRequestedEventArgs(dialogResult));
}
...
public class CloseRequestedEventargs : EventArgs
{
private readonly bool? _dialogResult;
public CloseRequestedEventargs(bool? dialogResult)
{
_dialogResult = dialogResult;
}
public bool DialogResult { get { return _dialogResult; } }
}
And handle it in the code-behind:
var vm = (MyViewModel)DataContext;
vm.CloseRequested += vm_CloseRequested;
...
private void vm_CloseRequested(object sender, CloseRequestedEventArgs e)
{
if (e.DialogResult.HasValue)
this.DialogResult = e.DialogResult; // sets the dialog result AND closes the window
else
this.Close();
}

Categories

Resources