I need to insert data from usercontrol into database.
I tried to set xml component into my model but it results in System.NullReferenceException.
Where is the problem ? How can I solve this?
usercontrol.cs:
public partial class League : UserControl
{
private Leagues _leagueVM;
public Leagues LeagueVM
{
get
{
_leagueVM.EnLeagueName = txtLeagueNameEN.Text;
_leagueVM.FaLeagueName = txtLeagueNameFA.Text;
_leagueVM.LeagueLogo = imgLogoLeague.Name;
return _leagueVM;
}
set
{
txtLeagueNameEN.Text = _leagueVM.EnLeagueName;
txtLeagueNameFA.Text = _leagueVM.FaLeagueName;
imgLogoLeague.Name = _leagueVM.LeagueLogo;
}
}
public League()
{
var leagueManager = Inject.Container.GetInstance<ILeagueService>();
InitializeComponent();
}
private void Image_MouseDown(object sender, MouseButtonEventArgs e)
{
FileDialog dialog = new OpenFileDialog();
dialog.ShowDialog();
}
private void btnInsertLeague_Click(object sender, RoutedEventArgs e)
{
var leagueManager = Inject.Container.GetInstance<ILeagueService>();
leagueManager.Add(LeagueVM);
}
}
xml:
<UserControl x:Class="Bet.UControl.UControls.League"
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:Bet.UControl.UControls"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800" Width="1255" Height="624">
<Grid Margin="10,0,10,10">
<GroupBox Header="New League" Background="#fff" HorizontalAlignment="Center" Height="151" Margin="10,10,0,0" VerticalAlignment="Top" Width="1215">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<Label Content="LeagueName (En) : " Foreground="Black" Width="111" FontFamily="Rockwell" Height="28"/>
<TextBox x:Name="txtLeagueNameEN" Width="199" Height="30" Margin="10,20,30,40" />
<Label Content="LeagueName (En) : " Foreground="Black" Width="111" FontFamily="Rockwell" Height="28"/>
<TextBox x:Name="txtLeagueNameFA" Width="199" Height="30" Margin="10,20,30,40" />
<Label Content="League Logo " Foreground="Black" Width="111" FontFamily="Rockwell" Height="28"/>
<Image x:Name="imgLogoLeague" Width="90" Height="85" Margin="5,0,0,0" Source="E:\MyProject\Bet\Bet\Assetes\adfg.png" MouseDown="Image_MouseDown"/>
<Button x:Name="btnInsertLeague" Content="Add" Height="Auto" Width="75" Margin="100,27,30,43" Click="btnInsertLeague_Click"/>
</StackPanel>
</GroupBox>
<DataGrid HorizontalAlignment="Left" Height="420" Margin="15,184,0,0" VerticalAlignment="Top" Width="1210"/>
</Grid>
It seems you missed to create a Leagues object and assign it to _leagueVM.
Should be easy to see if you use the debugger.
Related
I try to make a "email messenger". I have two windows. Main window, there is ribbon with bookmarks and one button (New message). This button invoke second window NewMessage. The Mainwindow is owner of the NewMessage window.
MainWindow:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
NewMessage newmessage = new NewMessage();
newmessage.Show();
}
}
}
MainWindow XAML:
<Window x:Class="Messenger.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:Messenger"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="New Message" Height="20" Width="80
" HorizontalAlignment="Left" Margin="35,46,0,0" VerticalAlignment="Top" Click="Button_Click" />
<TabControl HorizontalAlignment="Left" Height="254" Margin="34,44,0,0" VerticalAlignment="Top" Width="461" Background="{x:Null}" SelectedIndex="1">
<TabItem Header="Delivered" Visibility="Hidden" Width="80">
<Grid Background="#FFE5E5E5"/>
</TabItem>
<TabItem Header="Delivered" Visibility="Visible" Width="80">
<Grid Background="#FFE5E5E5"/>
</TabItem>
<TabItem Header="Sent" Width="80">
<Grid Background="#FFE5E5E5"/>
</TabItem>
<TabItem Header="Trash" Width="80">
<Grid Background="#FFE5E5E5"/>
</TabItem>
</TabControl>
</Grid>
NewMessage:
public partial class NewMessage : Window
{
public NewMessage()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}
NewMessage XAML:
<Window x:Class="Messenger.NewMessage"
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:Messenger"
mc:Ignorable="d"
Title="NewMessage" Height="351.047" Width="814.398">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="4*"/>
<ColumnDefinition Width="27*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="23*"/>
<RowDefinition Height="24*"/>
<RowDefinition Height="243*"/>
<RowDefinition Height="31*"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Content="Komu" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<TextBox Grid.Row="0" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Top" />
<Label Grid.Row="1" Content="Předmět" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<TextBox Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Top" />
<RichTextBox HorizontalAlignment="Left" Height="243" Grid.Row="2" VerticalAlignment="Top" Width="806" Grid.ColumnSpan="2">
<FlowDocument>
<Paragraph>
<Run Text="Sem zadejte text zprávy"/>
</Paragraph>
</FlowDocument>
</RichTextBox>
<Button Grid.Row="3" Content="Odeslat" Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Top" Width="75" Margin="0,5,90,0"/>
<Button Grid.Row="3" Content="Storno" Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Top" Width="75" Margin="0,5,10,0" Click="Button_Click"/>
</Grid>
I would like to, when I minimize NewMessage window, this window minimize to the bottom of MainWindow "taskbar". If you know gmail, there is the same principle. Any idea?
I have the following code :
<Window x:Class="WpfApplication3.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:WpfApplication3" xmlns:oxy="http://oxyplot.org/wpf"
xmlns:vm="clr-namespace:ViewModel;assembly=ViewModel"
Background="#FFDEDEDE"
WindowStyle="None"
AllowsTransparency="True"
WindowStartupLocation="CenterScreen"
mc:Ignorable="d"
Title="Compression Test" Height="1080" Width="1920">
<Window.Resources>
<vm:MainViewModel x:Key="vmMain"
sampleCount="100" />
</Window.Resources>
<Grid x:Name="gridUI">
<StackPanel Orientation="Vertical">
<StackPanel Height="100">
<Border Background="#FF8986D3" Height="100" Margin="0,0,0,30" >
<TextBlock Text="COMPRESSION TEST" FontFamily="Sans-serif" FontSize="30" Foreground="#FFF9F9F9" VerticalAlignment="Center" FontWeight="Medium" HorizontalAlignment="Center"/>
</Border>
</StackPanel>
<StackPanel Orientation="Horizontal" Height="auto">
<Border BorderBrush="White" BorderThickness="2" >
<StackPanel Orientation="Vertical" Width="200" Height="1080">
<Label FontSize="24" FontFamily="Sans-serif" FontWeight="Medium" Name="doc" Foreground="White" Background="#FFA39AD8" Width="200" HorizontalContentAlignment="Center" Height="43">Files</Label>
<Border BorderBrush="#FFD4D4D4" BorderThickness="0.5" Grid.Row="3"></Border>
<StackPanel Name="sp_doc" Margin="0,10,0,0" >
<StackPanel Orientation="Horizontal" Name="sp_sample_button" Grid.Row="0" Grid.Column="0">
<Image Source="pack://application:,,,/Resources/413.png" Height="40" Width="40" UseLayoutRounding="True" MouseDown="sampleDropDown" Cursor="Hand" Margin="5,0,0,0" Name="up_arrow"/>
<Image Source="pack://application:,,,/Resources/412.png" Height="40" Width="40" UseLayoutRounding="True" MouseDown="sampleDropDown" Cursor="Hand" Margin="5,0,0,0" Name="down_arrow" Visibility="Collapsed"/>
<!--<Button x:Name="sss" Click="sampleDropDown">s</Button>-->
<Label FontSize="18" FontFamily="Sans-serif" FontWeight="Light" Name="sam" Foreground="White" Margin="10">Samples</Label>
</StackPanel>
<StackPanel Orientation="Vertical" Name="sp_s">
</StackPanel>
<StackPanel Orientation="Horizontal" Grid.Column="1" Grid.Row="1">
<Image Source="pack://application:,,,/Resources/413.png" Height="40" Width="40" UseLayoutRounding="True" RenderTransformOrigin="-0.,0.558" MouseDown="reportDropDown" Cursor="Hand" Margin="5,0,0,0" Name="up_arrow1"/>
<Image Source="pack://application:,,,/Resources/412.png" Height="40" Width="40" UseLayoutRounding="True" Cursor="Hand" Margin="5,0,0,0" Name="down_arrow1" Visibility="Collapsed" MouseDown="reportDropDown"/>
<!--<Button Click="reportDropDown">r</Button>-->
<Label FontFamily="Sans-serif" FontWeight="Light" Foreground="White" FontSize="18" Margin="10">Reports</Label>
</StackPanel>
<StackPanel Orientation="Vertical" Name="sp_r">
</StackPanel>
</StackPanel>
</StackPanel>
</Border>
<StackPanel Width="1781">
<StackPanel Orientation="Horizontal" Background="#FFFDFDFD" Height="111">
<TextBox Name="sampleCount" Text="{Binding sampleCount, Source={StaticResource vmMain}, UpdateSourceTrigger=PropertyChanged}" Width="200"></TextBox>
<Button Cursor="Hand" Height="75" Width="75" Style="{StaticResource CircleButton}" FontFamily="Sans-Serif" FontSize="25" Foreground="White" Click="NewSample_Click" Content="+" Margin="20,0,0,0" Background="#FFACAABF" />
<StackPanel Margin="20,19,0,0">
<Image Source="pack://application:,,,/Resources/file512.png" Height="75" Width="75" UseLayoutRounding="True" Margin="0,0,0,0" MouseDown="CreateReport_Click" Cursor="Hand" SnapsToDevicePixels="True"/>
</StackPanel>
<Image Source="pack://application:,,,/Resources/play1.png" Height="75" Width="75" UseLayoutRounding="True" Margin="20,18,0,18" MouseDown="CreateReport_Click" Cursor="Hand" SnapsToDevicePixels="True"/>
<Image Source="pack://application:,,,/Resources/1131.png" Height="75" Width="75" UseLayoutRounding="True" Margin="1340,0,0,0" MouseDown="CreateReport_Click" Cursor="Hand"/>
</StackPanel>
<Frame x:Name="newSampleFrame" Content="" HorizontalAlignment="center" VerticalAlignment="center" Width="934" Height="456" NavigationUIVisibility="Hidden" RenderTransformOrigin="0.408,0.5" Visibility="Collapsed"/>
<Frame x:Name="reportFrame" Content="" HorizontalAlignment="Center" Height="842" VerticalAlignment="Center" Width="595" Margin="0,100,0,0" NavigationUIVisibility="Hidden"/>
<Frame x:Name="graphFrame" Content="" HorizontalAlignment="Center" Height="456" VerticalAlignment="Center" Width="934" NavigationUIVisibility="Hidden" Visibility="Collapsed"/>
</StackPanel>
</StackPanel>
</StackPanel>
</Grid>
</Window>
MainViewModel.cs :
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ViewModel
{
public class MainViewModel : ObservableObject
{
public MainViewModel()
{
}
private string[] sampleName;
private string _sampleCount;
public Data obj2 = new Data();
public string this[int pos]
{
get
{
return sampleName[pos];
}
set
{
sampleName[pos] = value;
}
}
public string sampleCount
{
get
{
return _sampleCount;
}
set
{
if (value != _sampleCount)
{
_sampleCount = value;
OnPropertyChanged("sampleCount");
Console.WriteLine("Test");
Console.WriteLine(value);
obj2.sampleCount = value;
SaveFile.saveFileMain(obj2);
}
}
}
}
}
And I have the following code that create a textblock whenever I click on the OK button :
window2.xaml.cs:
private void Ok_Click(object sender, MouseButtonEventArgs e)
{
MainWindow win = (MainWindow)Application.Current.MainWindow;
int i = 1; // counter for the name of each new textblock
string name = String.Concat("sample", i);
// add textblok to the document list of new samples
if (File_name.Text != "")
{
TextBlock sampleText = new TextBlock();
sampleText.Text = File_name.Text;
sampleText.FontSize = 14;
sampleText.FontFamily = new FontFamily("Sans-serif");
sampleText.FontWeight = FontWeights.DemiBold;
sampleText.Margin = new Thickness(20,0,0,0);
sampleText.Name = name;
sampleText.PreviewMouseDown += new MouseButtonEventHandler(test1);
sampleText.Visibility = System.Windows.Visibility.Collapsed;
//binding
Binding myBinding = new Binding();
myBinding.Source =
myBinding.Path = new PropertyPath("sampleName");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
sampleText.SetBinding(TextBlock.TextProperty, myBinding);
Grid.SetColumn(sampleText, 0);
win.sp_s.Children.Add(sampleText);
// checking if the drop down of sample is already open, if so it will show the last textblock with pressing the arrow button.
var textblockSample = win.sp_s.Children.OfType<TextBlock>().FirstOrDefault();
if (textblockSample.Visibility == System.Windows.Visibility.Visible)
{
sampleText.Visibility = System.Windows.Visibility.Visible;
}
}
i += 1; // increasing the loop of names by 1
this.Close();
}
Is it possible to use the same object that is initiated in xaml (vmMain) as a source for binding the textblock (sample text) to sampleName property?
Not sure why you don't set DataContext of your MainWindow to MainViewModel.
<Window.DataContext>
<StaticResourceExtension ResourceKey="vmMain" />
</Window.DataContext>
Or, you can even set DataContext via MainWindow's code behind, which you don't seem to intent to not keep it untouched.
Then to set binding source:
myBinding.Source = this.DataContext;
In the case you refused to set the DataContext, you still can:
myBinding.Source = this.FindResource("vmMain") as MainViewModel;
Not sure if I managed to solve your problem.
Edit
I just realised your binding is in window2. You should do this:
myBinding.Source = win.DataContext;
Similarly, myBinding.Source = this.FindResource("vmMain") as MainViewModel; should also be changed to myBinding.Source = win.FindResource("vmMain") as MainViewModel;.
This is provided you still have that MainWindow win = (MainWindow)Application.Current.MainWindow; line there.
I believe that what you are looking for is the resources property:
myBinding.Source = Resources["vmMain"];
Resource allows you to access the XAML-defined (or otherwise) resources for the current object - the window.
You can also access the resources of any FrameworkElement in the same manner.
EDIT: I hadn't noted the fact that the vmMain was in a different class. With this in mind, no there is no way to reference that object directly from Window2 as there may be multiple MainWindows so you'd have to pick which MainWindow instance the vmMain should be taken from.
What you can do, however is create vmMain in your Application object (App.xaml). This would then share that object across all FrameworkElements in your application. To access this you could use
myBinding.Source = Application.Currennt.Resources["vmMain"];
I have created a window which is a numbered keypad :
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Name="btnTotal" Width="280" Height="60" Grid.ColumnSpan="3" Grid.Row="0" Margin="10,10,10,10" Background="#302F37" Foreground="AntiqueWhite" FontSize="35"></TextBox>
<Button x:Name="btnZzero" Content="0" Width="80" Height="60" Grid.Column="0" Grid.Row="4" Margin="5,5,5,5" Background="#302F37" Foreground="White" Focusable="False" Click="btnZzero_Click"></Button>
<Button x:Name="btnOk" Content="OK" Width="80" Height="60" Grid.Column="1" Grid.Row="4" Margin="5,5,5,5" Click="btnOk_Click" Background="#FF8FC377" Focusable="False"></Button>
<Button x:Name="btnCancel" Content="Cancel" Width="80" Height="60" Grid.Column="2" Grid.Row="4" Margin="5,5,5,5" Click="cancel_Click" BorderBrush="Black" Background="#FFD64D4D" Focusable="False"></Button>
<Button x:Name="btnOne" Content="1" Width="80" Height="60" Grid.Column="0" Grid.Row="3" Margin="14,6,0,6" Focusable="False" Background="#302F37" Foreground="White" HorizontalAlignment="Left" Click="btnOne_Click"></Button>
<Button x:Name="btnTwo" Content="2" Width="80" Height="60" Grid.Column="1" Grid.Row="3" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White" Click="btnTwo_Click"/>
<Button x:Name="btnThree" Content="3" Width="80" Height="60" Grid.Column="2" Grid.Row="3" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White"/>
<Button x:Name="btnFour" Content="4" Width="80" Height="60" Grid.Column="0" Grid.Row="2" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White"></Button>
<Button x:Name="btnFive" Content="5" Width="80" Height="60" Grid.Column="1" Grid.Row="2" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White"></Button>
<Button x:Name="btnSix" Content="6" Width="80" Height="60" Grid.Column="2" Grid.Row="2" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White"></Button>
<Button x:Name="btnSeven" Content="7" Width="80" Height="60" Grid.Column="0" Grid.Row="1" Margin="12,5,9,6" Focusable="False" Background="#302F37" Foreground="White"></Button>
<Button x:Name="btnEight" Content="8" Width="80" Height="60" Grid.Column="1" Grid.Row="1" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White"></Button>
<Button x:Name="btnNine" Content="9" Width="80" Height="60" Grid.Column="2" Grid.Row="1" Margin="5,5,5,5" Focusable="False" Background="#302F37" Foreground="White"></Button>
Now, I would like to call this keypad at different times in my application to do different things.
IE I want to use it for a login screen :
<Window x:Class="WpfApplication2.MainLogin2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainLogin2" WindowState="Maximized" Width="1024" Height="768" WindowStyle="None" WindowStartupLocation="CenterScreen">
<Grid Background="#FF260538">
<Grid.RowDefinitions>
<RowDefinition Height="768" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1024" />
</Grid.ColumnDefinitions>
<TextBox Name="userIDTextBox" HorizontalAlignment="Left" Height="47" Margin="402,249,0,0" TextWrapping="Wrap" Text="User ID" VerticalAlignment="Top" Width="213" FontSize="30" PreviewMouseDown="userIDTextBox_PreviewMouseDown" />
<TextBox Name="passcodeTextBox" Height="47" Margin="402,317,0,0" TextWrapping="Wrap" Text="Passcode" VerticalAlignment="Top" Width="213" FontSize="30" HorizontalAlignment="Left" PreviewMouseDown="passcodeTextBox_PreviewMouseDown" />
<Button Content="OK" HorizontalAlignment="Left" Margin="402,386,0,0" VerticalAlignment="Top" Width="213" Height="59" FontSize="30" Click="okButton_Click"/>
<Button Content="CANCEL" HorizontalAlignment="Left" Margin="402,450,0,0" VerticalAlignment="Top" Width="213" Height="59" FontSize="30" Click="cancelButton_Click_1"/>
</Grid>
My problem is how do I pass the result from the keypad back to different text fields after I have clicked ok?
Here is the code behind the keypad window. I only have the number 1 working so far for testing:
namespace WpfApplication2
{
public partial class QuantityKeypad : Window
{
bool btnClicked = false;
string quantityResult = "";
public QuantityKeypad()
{
InitializeComponent();
}
private void cancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btnOk_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btnZzero_Click(object sender, RoutedEventArgs e)
{
}
private void btnOne_Click(object sender, RoutedEventArgs e)
{
if (btnClicked == true)
{
btnTotal.Text = "";
btnClicked = false;
}
quantityResult = quantityResult += "1";
btnTotal.Text = quantityResult;
}
private void btnTwo_Click(object sender, RoutedEventArgs e)
{
}
}
}
And here is the code for the login screen :
namespace WpfApplication2
{
public partial class MainLogin2 : Window
{
public MainLogin2()
{
InitializeComponent();
}
//OK button
private void okButton_Click(object sender, RoutedEventArgs e)
{
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
this.Close();
}
//Cancel button - takes user back to login screen
private void cancelButton_Click_1(object sender, RoutedEventArgs e)
{
this.Close();
}
//Removes text from login textboxes when clicked in
//opens instance of Quantitykeypad when clicking inside textbox
private void userIDTextBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
userIDTextBox.Text = "";
QuantityKeypad loginKeypad = new QuantityKeypad();
loginKeypad.Owner = this;
loginKeypad.ShowDialog();
}
//Removes text from passcode textboxe when clicked in
//opens instance of Quantitykeypad when clicking inside passcode textbox
private void passcodeTextBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
passcodeTextBox.Text = "";
QuantityKeypad loginKeypad = new QuantityKeypad();
loginKeypad.Owner = this;
loginKeypad.ShowDialog();
}
}
}
Terribly sorry if this is simple but I have been struggling for days now.
Thanks
You can make your private field quantityResult a publicly accessible property instead:
public string QuantityResult { get; private set; }
That way, you can read from it:
passcodeTextBox.Text = "";
QuantityKeypad loginKeypad = new QuantityKeypad();
loginKeypad.Owner = this;
loginKeypad.ShowDialog();
passcodeTextBox.Text = loginKeypad.QuantityResult;
I know there are a lot of question like this in the web, but believe me I spent on this a lot of hours and I still not success, I really will glad for any help!
I loading various images in run time and I want to show them in list box (small images, then the user should click on one of them and show him in real size).
my code is:
public partial class MainWindow : Window
{
int imageNumber = 0;
public List<String> ImagePath = new List<String>();
public MainWindow()
{
InitializeComponent();
lb_Images.ItemsSource = ImagePath;
}
private void bu_addImage_Click(object sender, RoutedEventArgs e)
{
addImageToListBox();
}
private void addImageToListBox()
{
imageNumber++;
if (imageNumber == 4) imageNumber = 0;
string directoryPath = AppDomain.CurrentDomain.BaseDirectory;
// load input image
string ImageFilename = directoryPath + "img";
ImageFilename += imageNumber.ToString();
ImageFilename += ".jpg";
ImagePath.Add(ImageFilename);
}
}
and the xaml is:
<Window x:Class="forQuestionWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="216" Width="519">
<Window.Resources>
<DataTemplate x:Key="ImageGalleryDataTemplate">
<Grid>
<Border BorderBrush="#FFFF9800" BorderThickness="1" Width="120" Height="120" Padding="5" Margin="5" CornerRadius="6">
<!--Bind Image Path in Image Control-->
<Image Source="{Binding ImagePath}" Stretch="Fill" HorizontalAlignment="Center">
<!--View Large Image on Image Control Tooltip-->
<Image.ToolTip>
<Grid>
<Image Source="{Binding ImagePath}" Stretch="Fill" HorizontalAlignment="Center" Height="200" Width="200"></Image>
</Grid>
</Image.ToolTip>
</Image>
</Border>
</Grid>
</DataTemplate>
<ItemsPanelTemplate x:Key="ImageGalleryItemsPanelTemplate">
<!--Display Images on UniformGrid Panel-->
<UniformGrid Rows="1" Columns="25" HorizontalAlignment="Center" VerticalAlignment="Stretch"/>
</ItemsPanelTemplate>
</Window.Resources>
<Grid>
<Canvas Height="177" HorizontalAlignment="Left" Name="canvas1" VerticalAlignment="Top" Width="497">
<ListBox Canvas.Left="6" Canvas.Top="5" Height="166" Name="lb_Images" Width="441"
BorderBrush="{x:Null}" DataContext="{Binding Source={StaticResource ImageGalleryDataTemplate}}"
ItemsSource="{Binding Source={StaticResource ImageGalleryItemsPanelTemplate}}">
</ListBox>
<Button Canvas.Left="453" Canvas.Top="26" Content="Add" Height="64" Name="bu_addImage" Width="38" Click="bu_addImage_Click" />
</Canvas>
</Grid>
</Window>
I know that the list box updated when I add image path to the list because if I debug I found some items under lb_Images.items, but I show nothing.
I'll glad for any help! thank you!!
Some notes
DataContext for ListBox it's not necessary, then you set ItemSource. Instead of set the ItemTemplate
In DataTemplate remove the {Binding ImagePath}, instead of write {Binding}, because in this case the elements of the DataTemplate inherit DataContext.
When you add new items to ListBox.Items, you must call ListBox.Items.Refresh() or use the ObservableCollection<T>, because:
ObservableCollection represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.
Try this example:
XAML
<Window.Resources>
<DataTemplate x:Key="ImageGalleryDataTemplate">
<Grid>
<Border BorderBrush="#FFFF9800" BorderThickness="1" Width="120" Height="120" Padding="5" Margin="5" CornerRadius="6">
<Image Source="{Binding}" Stretch="Fill" HorizontalAlignment="Center">
<Image.ToolTip>
<Grid>
<Image Source="{Binding}" Stretch="Fill" HorizontalAlignment="Center" Height="200" Width="200" />
</Grid>
</Image.ToolTip>
</Image>
</Border>
</Grid>
</DataTemplate>
<ItemsPanelTemplate x:Key="ImageGalleryItemsPanelTemplate">
<UniformGrid Rows="1" Columns="25" HorizontalAlignment="Center" VerticalAlignment="Stretch"/>
</ItemsPanelTemplate>
</Window.Resources>
<Grid>
<Canvas Height="177" HorizontalAlignment="Left" Name="canvas1" VerticalAlignment="Top" Width="497">
<ListBox Canvas.Left="6" Canvas.Top="5" Height="166" Name="lb_Images" Width="441"
ItemTemplate="{StaticResource ImageGalleryDataTemplate}"
ItemsSource="{Binding Path=ImagePath}">
</ListBox>
<Button Canvas.Left="453" Canvas.Top="26" Content="Add" Height="64" Name="bu_addImage" Width="38" Click="bu_addImage_Click" />
</Canvas>
</Grid>
Code-behind
public partial class MainWindow : Window
{
int imageNumber = 0;
public List<String> ImagePath = new List<String>();
public MainWindow()
{
InitializeComponent();
lb_Images.ItemsSource = ImagePath;
}
private void bu_addImage_Click(object sender, RoutedEventArgs e)
{
addImageToListBox();
}
private void addImageToListBox()
{
imageNumber++;
if (imageNumber == 4) imageNumber = 0;
string directoryPath = AppDomain.CurrentDomain.BaseDirectory;
// load input image
string ImageFilename = directoryPath + "img";
ImageFilename += imageNumber.ToString();
ImageFilename += ".jpg";
ImagePath.Add(ImageFilename);
lb_Images.Items.Refresh();
}
}
I am learning c# and I have been asked to work on a project using WPF, which I don't know much. We are using MUI as well.
I am trying to achieve a pretty basic task. I have two pages called ClientRNG.xamland ServerRNG.xaml. In ClientRNG.xaml I have two buttons and two textfield, when each button is pressed a random number is generated and it appears in a text box. In ServerRNG there are just one button and one textfield, with the same functionality as mentioned above.
So I'll end up with three different random numbers, one in ServerRNG.xaml and two in ClientRNG.
What i want to do is to pass these random numbers to another page called SSL.xaml.
The pages are created in MainWindow.xml:
<mui:ModernWindow.MenuLinkGroups>
<mui:LinkGroup DisplayName="network security">
<mui:LinkGroup.Links>
<mui:Link DisplayName="Home" Source="/Pages/Home.xaml" />
<mui:Link DisplayName="RNG" Source="/Pages/ClientRNG.xaml" />
<mui:Link DisplayName="3DES" Source="/Pages/3des.xaml" />
<mui:Link DisplayName="RSA" Source="/Pages/RSA.xaml" />
<mui:Link DisplayName="SHA-1" Source="/Pages/sha1.xaml" />
<mui:Link DisplayName="PKI Certificates" Source="/Pages/pki.xaml" />
<mui:Link DisplayName="SSL" Source="/Pages/SSL.xaml" />
</mui:LinkGroup.Links>
</mui:LinkGroup>
<mui:LinkGroup DisplayName="settings" GroupName="settings">
<mui:LinkGroup.Links>
<mui:Link DisplayName="software" Source="/Pages/Settings.xaml" />
</mui:LinkGroup.Links>
</mui:LinkGroup>
</mui:ModernWindow.MenuLinkGroups>
<mui:ModernWindow.TitleLinks>
<mui:Link DisplayName="settings" Source="/Pages/Settings.xaml" />
</mui:ModernWindow.TitleLinks>
Code in ClientRNG:
namespace NetworkSecuritySSLTest.Pages
{
/// <summary>
/// Interaction logic for RNG.xaml
/// </summary>
public partial class ClientRNG : UserControl
{
public ClientRNG()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Random r = new Random(1);
int number = r.Next(0, 100);
r1Out.Text = number.ToString();
SharingManager.GlobalValue = number;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Random r = new Random(3);
int number = r.Next(0, 100);
pmsOutC.Text = number.ToString();
}
here is the code I have in ServerRNG:
namespace NetworkSecuritySSLTest.Pages
{
/// <summary>
/// Interaction logic for RNG.xaml
/// </summary>
public partial class ServerRNG : UserControl
{
private SplitPage1 sp;
public ServerRNG()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Random r = new Random(2);
int number = r.Next(0, 100);
r2Out.Text = number.ToString();
SharingManager.GlobalValue = number;
}
}
}
and this is the code behind SSL class
namespace NetworkSecuritySSLTest.Pages
{
/// <summary>
/// Interaction logic for SplitPage1.xaml
/// </summary>
public partial class SplitPage1 : UserControl
{
private int r1FromClient;
public SplitPage1()
{
InitializeComponent();
SharingManager.ValueChanged += UpdateTextBox1;
SharingManager.ValueChanged += UpdateTextBox2;
}
public void UpdateTextBox1(object sender, NumericEventArgs e)
{
r1SSLBox.Text = e.Value.ToString(); // Update textBox
}
public void UpdateTextBox2(object sender, NumericEventArgs e)
{
r2SSLBox.Text = e.Value.ToString(); // Update textBox
}
}
}
here are the xaml:
'SplitPage1'
<UserControl x:Class="NetworkSecuritySSLTest.Pages.SplitPage1"
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:mui="http://firstfloorsoftware.com/ModernUI"
mc:Ignorable="d"
d:DesignWidth="766.507" Height="535">
<Grid Style="{StaticResource ContentRoot}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="6"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ScrollViewer>
<StackPanel>
<TextBlock Text="CLIENT" Style="{StaticResource Heading2}" />
<TextBlock x:Name="hello" Text="Hello Server. This is my Random Number and my Security Capabilities:" FontSize="12" FontStyle="Italic" Margin="0,10,0,0" UseLayoutRounding="False" TextWrapping="Wrap" />
<TextBlock x:Name="helloCont" Text="" FontSize="12" FontStyle="Italic" Margin="0,0,0,0" />
<TextBox x:Name ="r1SSLBox" HorizontalAlignment="Left" Height="57" Margin="10,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.498,0.404"/>
<TextBox x:Name ="r2SSLBox" HorizontalAlignment="Left" Height="57" Margin="10,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.498,0.404"/>
<TextBlock x:Name="VerifyDC" Text="I need to verify your Digital Certificate:" FontSize="12" FontStyle="Italic" Margin="0,10,0,0" />
<TextBlock x:Name="VerifyCont" Text="" FontSize="12" FontStyle="Italic" />
<TextBlock x:Name="MSK" Text="My Master Key is:" FontSize="12" FontStyle="Italic" Margin="0,10,0,0" />
<TextBlock x:Name="MSKCont" Text="" FontSize="12" FontStyle="Italic" />
</StackPanel>
</ScrollViewer>
<GridSplitter Grid.Column="1" />
<ScrollViewer Grid.Column="2 " Margin="{StaticResource SplitRight}">
<StackPanel>
<TextBlock Text="SERVER" Style="{StaticResource Heading2}" />
<TextBlock Text="Content goes here" />
</StackPanel>
</ScrollViewer>
<GridSplitter Grid.ColumnSpan="3" HorizontalAlignment="Left" Margin="0,23,0,0" VerticalAlignment="Top" Width="735"/>
<Button Content="Man-In-The-Middle-Attack" HorizontalAlignment="Left" VerticalAlignment="Top" Width="209" RenderTransformOrigin="0.055,0.397" Height="40" Margin="255,451,0,0" Grid.ColumnSpan="3" />
</Grid>
ClientRNG
<UserControl x:Class="NetworkSecuritySSLTest.Pages.ClientRNG"
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:mui="http://firstfloorsoftware.com/ModernUI"
mc:Ignorable="d"
d:DesignWidth="766.507" Height="535">
<Viewbox Stretch="None">
<Grid Style="{StaticResource ContentRoot}" Height="301" Margin="0" Width="435">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="0*"/>
</Grid.ColumnDefinitions>
<!-- TODO: set #SelectedSource -->
<mui:ModernTab Layout="Tab" Margin="0,52,0,0">
<mui:ModernTab.Links>
<!-- TODO: set #Source -->
<mui:Link DisplayName="Client" />
<mui:Link DisplayName="Server" Source="/Pages/ServerRNG.xaml" />
</mui:ModernTab.Links>
</mui:ModernTab>
<Button Content="GENERATE R# 1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.055,0.397" Height="26" Margin="10,52,0,0" FontSize="11" Click="Button_Click" />
<TextBox Name ="r1Out" HorizontalAlignment="Left" Height="57" Margin="10,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.498,0.404"/>
<Button Content="GENERATE MS" HorizontalAlignment="Left" VerticalAlignment="Top" Width="119" RenderTransformOrigin="0.055,0.397" Height="26" Margin="306,52,0,0" Click="Button_Click_2" />
<TextBox Name ="msOutC" HorizontalAlignment="Left" Height="57" Margin="306,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="119" RenderTransformOrigin="0.498,0.404"/>
<Button Content="GENERATE PMS" HorizontalAlignment="Left" VerticalAlignment="Top" Width="133" RenderTransformOrigin="0.055,0.397" Height="26" Margin="151,52,0,0" Click="Button_Click_1" />
<TextBox Name ="pmsOutC" HorizontalAlignment="Left" Height="57" Margin="151,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="133" RenderTransformOrigin="0.498,0.404"/>
<Label Content="Random Number Generator" HorizontalAlignment="Left" Height="19" Margin="10,10,0,0" VerticalAlignment="Top" Width="415" FontWeight="Bold"/>
</Grid>
</Viewbox>
and ServerRNG
<UserControl x:Class="NetworkSecuritySSLTest.Pages.ServerRNG"
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:mui="http://firstfloorsoftware.com/ModernUI"
mc:Ignorable="d"
d:DesignWidth="766.507" Height="535">
<Viewbox Stretch="None">
<Grid Style="{StaticResource ContentRoot}" Height="301" Margin="0" Width="435">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="0*"/>
</Grid.ColumnDefinitions>
<!-- TODO: set #SelectedSource -->
<mui:ModernTab Layout="Tab" Margin="0,52,0,0">
<mui:ModernTab.Links>
<!-- TODO: set #Source -->
<mui:Link DisplayName="Client" Source="/Pages/ClientRNG.xaml" />
<mui:Link DisplayName="Server" />
</mui:ModernTab.Links>
</mui:ModernTab>
<Button Name ="r2but" Content="GENERATE R# 2" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.055,0.397" Height="26" Margin="76,52,0,0" FontSize="11" Click="Button_Click_1" />
<TextBox Name ="r2Out" HorizontalAlignment="Left" Height="57" Margin="76,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.498,0.404"/>
<Button Content="GENERATE MS" HorizontalAlignment="Left" VerticalAlignment="Top" Width="119" RenderTransformOrigin="0.055,0.397" Height="26" Margin="249,52,0,0" />
<TextBox Name ="msOutS" HorizontalAlignment="Left" Height="57" Margin="249,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="119" RenderTransformOrigin="0.498,0.404"/>
<Label Content="Random Number Generator" HorizontalAlignment="Left" Height="19" Margin="10,10,0,0" VerticalAlignment="Top" Width="415" FontWeight="Bold"/>
</Grid>
</Viewbox>
Now I was trying to use the solution posted by Omribitan but i am still struggling
According to what you said in the comment section that SplitPage1 is already shown,
What you are doing in your code is creating a new instance of SplitPage1 and passing it your data
SplitPage1 sp = new SplitPage1(); // This is a new page, not the one currently shown in your application
sp.Setr1SSLBox(number); // it should set the text box in SSL page
So if you want to set the text of the currently displayed SplitPage1, you need to get it's reference. It's hard to say how because I can't see your entire code but this is what I would consider:
Using IoC container to resolve the current instance of SplitPage1.
According to your code seems like there is a third party creating these pages. If that's true, it could pass ServerRNG a reference of the SplitPage1 it's creating which you'll be able to use later, for example :
public partial class ServerRNG : UserControl
{
private SplitPage1 sp;
public ServerRNG(SplitPage1 splitPage) : this()
{
sp = splitPage; // Save a reference to the currently displayed `SplitPage1` page
}
public ServerRNG()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Random r = new Random(2);
int number = r.Next(0, 100);
r2Out.Text = number.ToString();
sp.Setr1SSLBox(number); // Set the correct instance's text
}
}
Create a class which will expose a static property and event that will fire when that property changes:
public class SharingManager
{
// Define a global static event to be fired when the value is changing
public static event EventHandler<NumericEventArgs> ValueChanged;
public static int GlobalValue
{
set
{
// Fire ValueChanged event
if (ValueChanged != null)
ValueChanged(null, new NumericEventArgs(value));
}
}
}
public class NumericEventArgs : EventArgs
{
public NumericEventArgs(int value)
{
Value = value;
}
public int Value { get; set; }
}
Register a handler in SplitPage1
public SplitPage1()
{
InitializeComponent();
SharingManager.ValueChanged += UpdateTextBox;
}
public void UpdateTextBox(object sender, NumericEventArgs e)
{
r1SSLBox.Text = e.Value.ToString(); // Update textBox
}
In Button_Click_1 on ServerNRG, update the value to fire the event
Random r = new Random(2);
int number = r.Next(0, 100);
r2Out.Text = number.ToString();
SharingManager.GlobalValue = number;
Hope this helps
you should work on WPF using the MVVM design pattern.
Its kinda annoying without MVVM framework
I suggest you to use http://caliburnmicro.codeplex.com/
use this tutorial to get started
http://www.mindscapehq.com/blog/index.php/2012/01/12/caliburn-micro-part-1-getting-started/
it also explains how to use the mediator pattern (using caliburn micros event aggerator) to pass values/commands between diffrent windows.
http://www.mindscapehq.com/blog/index.php/2012/2/1/caliburn-micro-part-4-the-event-aggregator/