I created a new WPF app in Visual Studio and I placed a button using the drag and drop editor but I can't access the button in my .cs file using
MainButton.Content = "Set output to red";
but I get an error
System.NullReferenceException: 'Object reference not set to an instance of an object.'
MainButton was null while running the application.
The drag and drop editor generated this xaml file
<Window x:Class="WpfApp1.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:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Border HorizontalAlignment="Center" VerticalAlignment="Center" BorderBrush="Black" BorderThickness="3">
<TextBlock x:Name="Output" Background="Transparent" TextAlignment="Center" TextWrapping="Wrap" Text="Output" Height="88" Width="264"/>
</Border>
<RadioButton x:Name="Option1" Content="Red Pill" HorizontalAlignment="Left" Margin="135,75,0,0" VerticalAlignment="Top" Checked="RadioButton_Checked" IsChecked="True"/>
<RadioButton x:Name="Option2" Content="Blue Pill" HorizontalAlignment="Left" Margin="536,72,0,0" VerticalAlignment="Top" Checked="RadioButton_Checked_1"/>
<Button x:Name="MainButton" Content="Set output to red" HorizontalAlignment="Left" Margin="279,100,0,0" VerticalAlignment="Top" Width="213" Height="41" Click="MainButton_Click"/>
</Grid>
</Window>
Here's the .cs file
using System.Windows;
using System.Windows.Media;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void MainButton_Click(object sender, RoutedEventArgs e)
{
if ((bool)Option1.IsChecked)
{
Output.Background = Brushes.Crimson;
}
else
{
Option2.IsChecked = true;
Output.Background = Brushes.DodgerBlue;
}
}
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
MainButton.Content = "Set output to red";
}
private void RadioButton_Checked_1(object sender, RoutedEventArgs e)
{
MainButton.Content = "Set output to blue";
}
}
}
I can access other things in the UI just fine like radio buttons and text blocks but not the button. Why could this be happening?
During the initialization phase, some variables are going to be null since it hasn't been reached in the call order. RadioButton_Checked is called through event before the button is constructed since it contains the Checked property.
A quick and easy fix is as follows: Check for null in your event calls.
private void RadioButton_Checked (object sender, RoutedEventArgs e)
{
if(MainButton != null)
MainButton.Content = "Set output to red";
}
private void RadioButton_Checked_1 (object sender, RoutedEventArgs e)
{
if (MainButton != null)
MainButton.Content = "Set output to blue";
}
Of course, there are better ways to handle this. You could set checked on a separate event, Initialized, which will handle it much cleaner.
Related
I'm trying to implement Drag & Drop with files on a ListBox which is contained in a Window of an Avalonia project.
As I couldn't get it working and I thought that ListBox perhaps is a special case, I tried to make a similar example like the one from ControlCatalogStandalone.
While the code in ControlCatalogStandalone works as expected, virtually the same code in my test application doesn't work properly.
The relevant code in ControlCatalogStandalone belongs to a UserControl, where in my application it belongs to the MainWindow. Could this be the cause for the misbehavior?
I created a new Avalonia MVVM Application based on the NuGet packages 0.9.11 in Visual Studio 2019.
I also tried version 0.10.0-preview2 in vain.
This is the XAML file:
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:DragAndDropTests.ViewModels;assembly=DragAndDropTests"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Width="400" Height="200"
x:Class="DragAndDropTests.Views.MainWindow"
Icon="/Assets/avalonia-logo.ico"
Title="DragAndDropTests">
<Design.DataContext>
<vm:MainWindowViewModel/>
</Design.DataContext>
<StackPanel Orientation="Vertical" Spacing="4">
<TextBlock Classes="h1">Drag+Drop</TextBlock>
<TextBlock Classes="h2">Example of Drag+Drop capabilities</TextBlock>
<StackPanel Orientation="Horizontal"
Margin="0,16,0,0"
HorizontalAlignment="Center"
Spacing="16">
<Border BorderBrush="{DynamicResource ThemeAccentBrush}" BorderThickness="2" Padding="16" Name="DragMe">
<TextBlock Name="DragState">Drag Me</TextBlock>
</Border>
<Border Background="{DynamicResource ThemeAccentBrush2}" Padding="16"
DragDrop.AllowDrop="True">
<TextBlock Name="DropState">Drop some text or files here</TextBlock>
</Border>
</StackPanel>
</StackPanel>
</Window>
And this is the Code Behind:
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Markup.Xaml;
using System;
using System.Diagnostics;
namespace DragAndDropTests.Views
{
public class MainWindow : Window
{
private TextBlock _DropState;
private TextBlock _DragState;
private Border _DragMe;
private int DragCount = 0;
public MainWindow()
{
Debug.WriteLine("MainWindow");
InitializeComponent();
#if DEBUG
this.AttachDevTools();
#endif
_DragMe.PointerPressed += DoDrag;
AddHandler(DragDrop.DropEvent, Drop);
AddHandler(DragDrop.DragOverEvent, DragOver);
}
private async void DoDrag(object sender, Avalonia.Input.PointerPressedEventArgs e)
{
Debug.WriteLine("DoDrag");
DataObject dragData = new DataObject();
dragData.Set(DataFormats.Text, $"You have dragged text {++DragCount} times");
var result = await DragDrop.DoDragDrop(e, dragData, DragDropEffects.Copy);
switch (result)
{
case DragDropEffects.Copy:
_DragState.Text = "The text was copied"; break;
case DragDropEffects.Link:
_DragState.Text = "The text was linked"; break;
case DragDropEffects.None:
_DragState.Text = "The drag operation was canceled"; break;
}
}
private void DragOver(object sender, DragEventArgs e)
{
Debug.WriteLine("DragOver");
// Only allow Copy or Link as Drop Operations.
e.DragEffects = e.DragEffects & (DragDropEffects.Copy | DragDropEffects.Link);
// Only allow if the dragged data contains text or filenames.
if (!e.Data.Contains(DataFormats.Text) && !e.Data.Contains(DataFormats.FileNames))
e.DragEffects = DragDropEffects.None;
}
private void Drop(object sender, DragEventArgs e)
{
Debug.WriteLine("Drop");
if (e.Data.Contains(DataFormats.Text))
_DropState.Text = e.Data.GetText();
else if (e.Data.Contains(DataFormats.FileNames))
_DropState.Text = string.Join(Environment.NewLine, e.Data.GetFileNames());
}
private void InitializeComponent()
{
Debug.WriteLine("InitializeComponent");
AvaloniaXamlLoader.Load(this);
_DropState = this.Find<TextBlock>("DropState");
_DragState = this.Find<TextBlock>("DragState");
_DragMe = this.Find<Border>("DragMe");
}
}
}
Drag & Drop within the application works well in ControlCatalogStandalone and in my application.
The succession of events is DoDrag, DragOver, DragOver, …, Drop in this case.
Dragging a file from Windows Explorer to the ControlCatalogStandalone works well.
The succession of events is DragOver, DragOver, …, Drop
Dragging a file from Windows Explorer to my application doesn't work.
None of the expected events is called here.
What's wrong with my test application?
I have a Window class called MainWindow, and in its constructor, builds a default Page class I call, MonitorPage that populates my window with this page at launch. In my MainWindow, I have three buttons that act as page tabs or menu buttons that upon clicking them will create an instance of a different Page class, in my case I have three unique pages. MonitorPage, DataBasePage, HelpPage. In my MainWindow, I want to "grey-out" the tab button when that corresponding page is up. I have a method in MainWindow called, PageState(), that tries to identify which page is currently up to enable or disable and grey out the tabs. My problem is that I get a NullReferenceException in my method at the first IF check.
The Error I'm Getting:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Windows.Controls.ContentControl.Content.get returned null.
C#:
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Windows.Media;
namespace EyeInTheSky
{
/// <summary>
/// Interaction logic for MainWindow.xaml + backend code for FileSystemWatcher project
/// </summary>
public partial class MainWindow : Window
{
#region Fields
private FileSystemWatcher _watcher = new FileSystemWatcher();
private ObservableCollection<string[]> _eventList = new ObservableCollection<string[]>();
#endregion
public MainWindow()
{
InitializeComponent();
Main.Content = new MonitorPage(ref _watcher, ref _eventList);
PageState();
}
private void PageState()
{
if (Main.Content.GetType() == typeof(MonitorPage))
{
Menu_MonitorButton.IsEnabled = false;
Menu_MonitorButton.Background = new SolidColorBrush(Color.FromRgb(88, 88, 95));
Menu_DataBaseButton.IsEnabled = true;
Menu_HelpButton.IsEnabled = true;
}
else if (Main.GetType() == typeof(DataBasePage))
{
Menu_MonitorButton.IsEnabled = true;
Menu_DataBaseButton.IsEnabled = false;
Menu_DataBaseButton.Background = new SolidColorBrush(Color.FromRgb(88, 88, 95));
Menu_HelpButton.IsEnabled = true;
}
else
{
Menu_MonitorButton.IsEnabled = true;
Menu_DataBaseButton.IsEnabled = true;
Menu_HelpButton.IsEnabled = false;
Menu_HelpButton.Background = new SolidColorBrush(Color.FromRgb(88, 88, 95));
}
}
private void Menu_MonitorButton_Click(object sender, RoutedEventArgs e)
{
PageState();
Main.Content = new MonitorPage(ref _watcher, ref _eventList);
}
private void MenuStrip_DataBaseButton_Click(object sender, RoutedEventArgs e)
{
PageState();
Main.Content = new DataBasePage(ref _eventList);
}
private void MenuStrip_HelpButton_Click(object sender, RoutedEventArgs e)
{
PageState();
Main.Content = new HelpPage();
}
}
}
XAML:
<Window x:Name="Home" x:Class="EyeInTheSky.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:EyeInTheSky"
xmlns:System="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="Eye In The Sky - Windows File System Watcher" Height="450" Width="1105" WindowStartupLocation="CenterScreen" ResizeMode="NoResize" TextOptions.TextFormattingMode="Ideal" Background="#FF39393E" Foreground="#FFE4E4E4" FontFamily="Roboto">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="27*"/>
<RowDefinition Height="394*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="240*"/>
<ColumnDefinition Width="859*"/>
</Grid.ColumnDefinitions>
<Frame x:Name="Main" Height="421" VerticalAlignment="Top" Grid.RowSpan="2" Grid.ColumnSpan="2" Panel.ZIndex="1"/>
<DockPanel HorizontalAlignment="Left" Height="27" LastChildFill="False" VerticalAlignment="Top" Width="240" Panel.ZIndex="10000">
<StackPanel x:Name="Menu" Orientation="Horizontal" HorizontalAlignment="Left" Height="27" VerticalAlignment="Top" Width="240" Background="#FF4E4E53">
<Button x:Name="Menu_MonitorButton" Content="Monitor" Width="80" Click="Menu_MonitorButton_Click" Background="#FF4E4E53" BorderBrush="#FF585858" Foreground="LightGray" BorderThickness="1,0"/>
<Button x:Name="Menu_DataBaseButton" Content="Data Base" Width="80" Click="MenuStrip_DataBaseButton_Click" Background="#FF4E4E53" BorderBrush="#FF585858" Foreground="LightGray" BorderThickness="1,0"/>
<Button x:Name="Menu_HelpButton" Content="About" Width="80" Click="MenuStrip_HelpButton_Click" Background="#FF4E4E53" BorderBrush="#FF585858" Foreground="LightGray" Padding="0,1,1,1" BorderThickness="1,0,2,0"/>
</StackPanel>
</DockPanel>
</Grid>
</Window>
I develop UWP app with C# and XAML. I try to implement drag&drop functionality.
Here is a simple app to demonstrate how I try to do it. The app has two borders - one border is dragged, and second one is for drop. Also I write informaton about events to output.
Version 1 (using CanDrag=true on a dragged item)
<Page x:Class="UWP_DragDrop.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UWP_DragDrop"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Border x:Name="draggedItem"
Grid.Row="0"
Height="100"
Width="150"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="Red"
CanDrag="True"
DragStarting="draggedItem_DragStarting"
DropCompleted="draggedItem_DropCompleted">
<TextBlock Text="Drag this item"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Border>
<Border x:Name="dropArea"
Grid.Row="1"
Height="100"
Width="150"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="Blue"
AllowDrop="True"
DragEnter="dropArea_DragEnter"
Drop="dropArea_Drop">
<TextBlock Text="Drop here"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Border>
</Grid>
using System.Diagnostics;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace UWP_DragDrop
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void draggedItem_DragStarting(UIElement sender, DragStartingEventArgs args)
{
Debug.WriteLine("draggedItem_DragStarting");
}
private void draggedItem_DropCompleted(UIElement sender, DropCompletedEventArgs args)
{
Debug.WriteLine("draggedItem_DropCompleted");
}
private void dropArea_DragEnter(object sender, DragEventArgs e)
{
Debug.WriteLine("dropArea_DragEnter");
e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Copy;
}
private void dropArea_Drop(object sender, DragEventArgs e)
{
Debug.WriteLine("dropArea_Drop");
}
}
}
1) It works correctly when I run it in Visual Studio for LocalMachine and for Simulator (but only for mouse input). In output I have the following:
draggedItem_DragStarting
dropArea_DragEnter
dropArea_Drop
draggedItem_DropCompleted
2) When I try to run it in Simulator (touch mode) - I can't drag item. No one event is fired (output is empty)
3) When I try to run it in Windows 10 Mobile emulator, it does not work. What I see in output is:
draggedItem_DragStarting
draggedItem_DropCompleted
As soon as I move the element - DropCompleted event fires.
Version 2 (using StartDragAsync)
I removed CanDrag=true for dragged item, and start drag operation by StartDragAsync.
<Page x:Class="UWP_DragDrop.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UWP_DragDrop"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Border x:Name="draggedItem"
Grid.Row="0"
Height="100"
Width="150"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="Red"
PointerMoved="draggedItem_PointerMoved"
DragStarting="draggedItem_DragStarting">
<TextBlock Text="Drag this item"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Border>
<Border x:Name="dropArea"
Grid.Row="1"
Height="100"
Width="150"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="Blue"
AllowDrop="True"
DragEnter="dropArea_DragEnter"
Drop="dropArea_Drop">
<TextBlock Text="Drop here"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Border>
</Grid>
using System.Diagnostics;
using Windows.ApplicationModel.DataTransfer;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
namespace UWP_DragDrop
{
public sealed partial class MainPage : Page
{
IAsyncOperation<DataPackageOperation> _dragOperation;
public MainPage()
{
this.InitializeComponent();
}
private void draggedItem_PointerMoved(object sender, PointerRoutedEventArgs e)
{
if (e.Pointer.IsInContact && (_dragOperation == null))
{
Debug.WriteLine("draggedItem_StartDragAsync");
_dragOperation = draggedItem.StartDragAsync(e.GetCurrentPoint(draggedItem));
_dragOperation.Completed = DragCompleted;
}
}
private void DragCompleted(IAsyncOperation<DataPackageOperation> asyncInfo, AsyncStatus asyncStatus)
{
_dragOperation = null;
Debug.WriteLine("draggedItem_DragCompleted");
}
private void draggedItem_DragStarting(UIElement sender, DragStartingEventArgs args)
{
Debug.WriteLine("draggedItem_DragStarting");
}
private void dropArea_DragEnter(object sender, DragEventArgs e)
{
Debug.WriteLine("dropArea_DragEnter");
e.AcceptedOperation = DataPackageOperation.Copy;
}
private void dropArea_Drop(object sender, DragEventArgs e)
{
Debug.WriteLine("dropArea_Drop");
}
}
}
1) Desktop and Simulator (mouse mode) works.
2) Simulator (touch mode) now works too.
3) Windows 10 mobile emulator does not work. DropCompleter fires right after DragStarting again.
How can I make drag&drop work on Windows 10 mobile? Why version 1 does not work in scenario 2 and 3, and version 2 does not work in scenario 3?
Unfortunately, it seems like customize drag is currently not supported on emulator and mobile yet. Details please reference this known issue. As Raymond mentioned:
You can drag/drop items within a listview, and any UI element can be a drop target, but you don't get dragging to another process or drag customization.
At this time windows 10 doesn't support a full-fledged drag and drop feature.
I have an array of combo boxes, and once each combo box is populated with items, I want the first item to be selected automatically. SO I do this:
all_transition_boxes[slide_item].SelectedItem = all_transition_boxes[slide_item].Items[0];
but then later I can not change the index anymore if I want to select some other item. It seems that the index is permanently set to zero. I tried to use SelectedItem instead of SelectedIndex but it doesn't work at all. I would appreciate any help.
//populate each combobox with corresponding elements
for (int i = 0; i < slide_transitions.Count; i++)
{
all_transition_boxes[slide_item].Items.Add("Transition " + (i + 1));
}
all_transition_boxes[slide_item].SelectedItem = all_transition_boxes[slide_item].Items[0];
I have created a sample code to replicate your issue, please check it.
A form with a combobox and two buttons:
<Window x:Class="WpfApplication1.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:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" Activated="Window_Activated">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="329*"/>
<ColumnDefinition Width="34*"/>
<ColumnDefinition Width="154*"/>
</Grid.ColumnDefinitions>
<ComboBox x:Name="comboBox" HorizontalAlignment="Left" Margin="146,78,0,0" VerticalAlignment="Top" Width="120"/>
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="101,185,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
<Button x:Name="button1" Content="Button" HorizontalAlignment="Left" Margin="266,185,0,0" VerticalAlignment="Top" Width="75" Grid.ColumnSpan="2" Click="button1_Click"/>
</Grid>
</Window>
And the form´s code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Activated(object sender, EventArgs e)
{
var items = new List<string>();
for (var i = 0; i < 10; i++)
{
items.Add("Item" + i);
}
comboBox.ItemsSource = items;
comboBox.SelectedItem = "Item0";
}
private void button_Click(object sender, RoutedEventArgs e)
{
comboBox.SelectedItem = "Item5";
}
private void button1_Click(object sender, RoutedEventArgs e)
{
comboBox.SelectedItem = "Item9";
}
}
}
On your ComboBox (in XAML) set:
SelectedIndex = "0"
You can set it as a setter in a style that is applied to all instances of ComboBox in your array.
I am attempting to create a program in which the User can create multiple profiles. These profiles can be accessed via buttons that appear as each profile is completed.
My problem:
I have no clue how to make the created buttons persist after the program is exited(I need to save the buttons?)
Visually, this is program's process: 1) Enter your information, click continue 2) View a display page of what you entered, click done. 3) This adds a button to the final window, the button of course takes you to 4) Your profile you just created.
After this, the program ends and nothing is saved. I'm fairly new to c# and am quite confused on how to "save" multiple buttons without massively complicating the code. I'm a complete noob to c# and have a little Java experience. Am I going about this correctly? I'm pretty sure its possible but have no idea to go about it.
I will include my code below. I'm working in visual studios 2012. any help would be appreciated!
MainWindow XAML:
<Window x:Class="VendorMain.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Label Content="FirstName" HorizontalAlignment="Left" Margin="63,45,0,0" VerticalAlignment="Top"/>
<Label Content="LastName" HorizontalAlignment="Left" Margin="63,71,0,0" VerticalAlignment="Top"/>
<Label Content="Image" HorizontalAlignment="Left" Margin="63,102,0,0" VerticalAlignment="Top"/>
<Image Name="imgPhoto" Stretch="Fill" Margin="63,133,303,69"></Image>
<Button Name="UploadImageButton" Content="Upload Image" HorizontalAlignment="Left" Margin="130,105,0,0" VerticalAlignment="Top" Width="84" Click="UploadImageButton_Click"/>
<TextBox Name="AssignFirstName" Text="{Binding SettingFirstname}" HorizontalAlignment="Left" Height="23" Margin="130,48,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" />
<TextBox Name="AssignLastName" Text="{Binding SettingLastName}" HorizontalAlignment="Left" Height="23" Margin="130,75,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<Button Name="ContinueToDisplayWindow" Content="Continue" HorizontalAlignment="Left" Margin="409,288,0,0" VerticalAlignment="Top" Width="75" Click="ContinueToDisplayWindow_Click" />
</Grid>
MainWindow Code:
namespace VendorMain
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void UploadImageButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.Title = "Select a picture";
op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
"JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
"Portable Network Graphic (*.png)|*.png";
if (op.ShowDialog() == true)
{
imgPhoto.Source = new BitmapImage(new System.Uri(op.FileName));
//SettingImage.Source = imgPhoto.Source;
}
}
private void ContinueToDisplayWindow_Click(object sender, RoutedEventArgs e)
{
DisplayPage displaypg = new DisplayPage();
displaypg.DpFirstName.Content = AssignFirstName.Text;
displaypg.DpLastName.Content = AssignLastName.Text;
displaypg.DpImage.Source = imgPhoto.Source;
displaypg.Show();
}
}
}
DisplayPage XAML:
<Window x:Class="VendorMain.DisplayPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="DisplayPage" Height="300" Width="525">
<Grid>
<Label Name="DpFirstName" Content="{Binding getFirstNamePermenent}" HorizontalAlignment="Left" Margin="86,55,0,0" VerticalAlignment="Top"/>
<Label Name="DpLastName" Content="{Binding getLastNamePermenent}" HorizontalAlignment="Left" Margin="87,80,0,0" VerticalAlignment="Top"/>
<Image Name="DpImage" HorizontalAlignment="Left" Height="100" Margin="94,111,0,0" VerticalAlignment="Top" Width="100"/>
<Button Name="ButtonizeThisProfile_Button" Content="Done" HorizontalAlignment="Left" Margin="420,238,0,0" VerticalAlignment="Top" Width="75" Click="ButtonizeThisProfile_Button_Click"/>
</Grid>
DisplayPage Code:
namespace VendorMain
{
/// <summary>
/// Interaction logic for DisplayPage.xaml
/// </summary>
public partial class DisplayPage : Window
{
public Button bot1;
public DisplayPage()
{
InitializeComponent();
}
private void newBtn_Click(object sender, RoutedEventArgs e)
{
carryToFinalView();
}
private void ButtonizeThisProfile_Button_Click(object sender, RoutedEventArgs e)
{
UserProfiles uPro = new UserProfiles();
System.Windows.Controls.Button newBtn = new Button();
newBtn.Content = "Person1";
newBtn.Name = "NewProfileButtonAccess";
newBtn.Click += new RoutedEventHandler(newBtn_Click);
uPro.ButtonArea.Children.Add(newBtn);
uPro.Show();
}
public void carryToFinalView()
{
DisplayPage displaypg = new DisplayPage();
displaypg.DpFirstName.Content = DpFirstName.Content;
displaypg.DpLastName.Content = DpLastName.Content;
displaypg.DpImage.Source = DpImage.Source;
displaypg.Show();
}
}
}
UserProfile XAML:
<Window x:Class="VendorMain.UserProfiles"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="UserProfiles" Height="300" Width="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width=".8*" />
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="6*"/>
<RowDefinition Height="11*"/>
</Grid.RowDefinitions>
<Label Content="User Profiles: " HorizontalAlignment="Left" Margin="37,47,0,0" VerticalAlignment="Top"/>
<StackPanel Name="ButtonArea" Grid.Column="2" Grid.Row="2">
</StackPanel>
<Button Name="AddAnotherProfileButton" Content="Button" HorizontalAlignment="Left" Margin="35,146,0,0" Grid.Row="1" VerticalAlignment="Top" Width="75" Click="AddAnotherProfileButton_Click"/>
</Grid>
UserProfile Code:
namespace VendorMain
{
public partial class UserProfiles : Window
{
public UserProfiles()
{
InitializeComponent();
}
private void AddAnotherProfileButton_Click(object sender, RoutedEventArgs e)
{
MainWindow mw = new MainWindow();
mw.Show();
}
}
}
As a self proclaimed 'noob', I fear that you won't receive an answer here. I certainly don't have time to repeatedly come back to answer a whole continuing stream of related questions. I also don't have time to provide you with a complete solution. However, I am happy to provide you with sort of 'pseudo code' to at least point you in the right direction... you will have to do a lot of this yourself.
So first things first, as mentioned in a comment, although it is possible, we don't generally save the UI Button objects, but instead we save the data that relates to the user profiles. Therefore, if you haven't done this already, create a User class that has all of the relevant properties. Implement the INotifyPropertyChanged Interface in it and add the SerializableAttribute to the class definition... this will enable you to save this class type as binary data.
Next, in your UI, don't add each Button in xaml... there's a better way. One way or another, add a collection property of type User or whatever your class is called, and set this as the ItemsSource of a ListBox. The idea here is to add a DataTemplate for your User type which will display each of the User items in the collection as a Button:
<DataTemplate x:Key="UserButtonTemplate" DataType="{x:Type DataTypes:User}">
<Button Text="{Binding Name}" Width="75" Click="AddAnotherProfileButton_Click" />
</DataTemplate>
You can find out more about DataTemplates in the Data Templates article.
Implementing this collection allows you to have and display any number of user profiles in your UI, rather than being restricted by screen size as your original example would be.
Now finally, on to saving the data... this can be achieved relatively simply using the following code:
try
{
using (Stream stream = File.Open("ProfileData.bin", FileMode.Create))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter .Serialize(stream, usersList);
}
}
catch { }
One thing to note is that WPF wants us to use the ObservableCollection<T> class when displaying data in the UI, but this class causes problems when serializing data with this method... therefore, you will need to convert your ObservableCollection<T> to a List<T> or similar. However, this can be easily achieved:
List<User> usersList = users.ToList();
You can find out how to de-serialize your data from the C# Serialize List tutorial. You would deserialize (or load the data from the saved file) each time your application starts and re-save the file each time the program closes. You can add an event handler to the Application.Deactivated Event or the Window.Closing which gets called when the application closes, so you can put your code to save the file in there.
Well, I took longer and wrote more than I had expected, so I hope that helps.