Get data from another window - c#

Project Informations
Windows Presentation Foundation Project
C# as programming language
Description
Is it possible to receive data from an user input in Window1 and show this input in MainWindow?
I will open the user input as a file from Window1 and will show the content of it in the RichTextBox of MainWindow.
Window1
<Window x:Name="window1" x:Class="Writer.Window1"
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:Writer"
mc:Ignorable="d"
Title="New" Height="130" Width="600" WindowStyle="None" WindowStartupLocation="CenterScreen" ResizeMode="CanMinimize">
<Grid Margin="0,0,0,-2">
<Rectangle HorizontalAlignment="Center" Height="30" Stroke="Black" VerticalAlignment="Top" Width="600" Fill="Black"/>
<Label Content="Open" HorizontalAlignment="Left" Margin="0,2,0,0" VerticalAlignment="Top" Foreground="White"/>
<Button Content="X" Margin="579,5,10,0" VerticalAlignment="Top" Background="Black" Foreground="White" BorderBrush="Black" ToolTip="Exit" Focusable="False" IsTabStop="False" Click="Button_Click"/>
<Label Content="Select the path" HorizontalAlignment="Left" Margin="0,35,0,0" VerticalAlignment="Top"/>
<TextBox HorizontalAlignment="Left" Margin="5,61,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" IsTabStop="False"/>
<Button Content="Select" HorizontalAlignment="Left" Margin="5,84,0,0" VerticalAlignment="Top" BorderBrush="White" Background="#FFADADAD" Width="45"/>
</Grid>
</Window>
MainWindow
<Window x:Name="MainWindow1" x:Class="Writer.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:Writer"
mc:Ignorable="d"
Title="Writer" Height="450" Width="800" WindowStyle="None" WindowStartupLocation="CenterScreen" ResizeMode="CanMinimize">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="164*"/>
<RowDefinition Height="83*"/>
<RowDefinition Height="203*"/>
</Grid.RowDefinitions>
<Rectangle HorizontalAlignment="Center" Height="30" Stroke="Black" VerticalAlignment="Top" Width="800" Fill="Black"/>
<Label Content="Writer" HorizontalAlignment="Left" Margin="0,2,0,0" VerticalAlignment="Top" Foreground="White"/>
<Button Content="_" HorizontalAlignment="Left" Margin="765,5,0,0" VerticalAlignment="Top" Background="Black" Foreground="White" BorderBrush="Black" Focusable="False" ToolTip="Minimize" IsTabStop="False" ClickMode="Press" Click="Button_Click_1"/>
<Button Content="X" Margin="779,5,10,0" VerticalAlignment="Top" Background="Black" Foreground="White" BorderBrush="Black" ToolTip="Exit" Focusable="False" IsTabStop="False" Click="Button_Click"/>
<Menu Margin="0,30,0,114" Height="20">
<MenuItem Header="File">
<MenuItem Header="New">
<MenuItem.Icon>
<Image Source="/file-added.svg"/>
</MenuItem.Icon>
</MenuItem>
<MenuItem Header="Open" Click="MenuItem_Click"/>
<MenuItem Header="Open from server"/>
<MenuItem Header="Save"/>
<MenuItem Header="Save as"/>
<MenuItem Header="Close file"/>
<MenuItem Header="Close folder"/>
</MenuItem>
<MenuItem Header="Start">
<MenuItem Header="Font">
<MenuItem Header="Font"/>
<MenuItem Header="Family"/>
<MenuItem Header="Size"/>
</MenuItem>
<Separator/>
<MenuItem Header="Bold"/>
<MenuItem Header="Italic"/>
<MenuItem Header="Underline"/>
<MenuItem Header="Strikethrough"/>
</MenuItem>
<MenuItem Header="Insert">
<MenuItem Header="New site"/>
</MenuItem>
<MenuItem Header="Layout">
</MenuItem>
<MenuItem Header="View">
</MenuItem>
<MenuItem Header="Help"/>
</Menu>
<RichTextBox x:Name="RichTextBox1" Margin="0,50,0,0" BorderBrush="White" Cursor="Arrow" IsTabStop="False" Grid.RowSpan="3" FontFamily="Segoe UI" BorderThickness="0,0,0,0">
<FlowDocument>
<Paragraph>
<Run Text=""/>
</Paragraph>
</FlowDocument>
</RichTextBox>
</Grid>
</Window>

Yes, there is a way.
Implement a public method in Window1 that gives you the data.
Then use the reference to Window1 and call that method.
If MainWindow does not have a reference to Window1, give it the reference.
Here's an example. It assumes that you open the second window from within the main window.
In addition to the CC-BY-SA license of Stack Overflow, I license this as CC-0 for anyone who needs this code in one of his projects.
MainWindow.xaml
<Window x:Class="GetDataFromOtherWindow.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"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<StackPanel>
<Button Content="Open other window" Click="Button_Click" />
<Button Content="Get data from other window" Click="Button_Click_1" />
</StackPanel>
</Window>
MainWindow.xaml.cs
using System.Windows;
namespace GetDataFromOtherWindow
{
public partial class MainWindow : Window
{
private Window1? otherWindow;
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
otherWindow = new Window1();
otherWindow.Show();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (otherWindow != null)
{
MessageBox.Show(otherWindow.GetData());
}
}
}
}
Window1.xaml
<Window x:Class="GetDataFromOtherWindow.Window1"
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"
mc:Ignorable="d"
Title="Window1" Height="141" Width="400">
<StackPanel>
<RichTextBox Name="richBox">
<FlowDocument>
<Paragraph>
<Run Text="This is some text"/>
</Paragraph>
</FlowDocument>
</RichTextBox>
</StackPanel>
</Window>
Window1.xaml.cs
using System.Windows;
using System.Windows.Documents;
namespace GetDataFromOtherWindow
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
public string GetData()
{
TextRange textRange = new TextRange(
richBox.Document.ContentStart,
richBox.Document.ContentEnd
);
return textRange.Text;
}
}
}
Note that this is not very MVVM-friendly, because this code has no model which would know about the business logic.
As per the comments, if you want to show the data after closing Window1, you can do this:
MainWindow.xaml.cs
using System.Windows;
namespace GetDataFromOtherWindow
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var otherWindow = new Window1();
otherWindow.ShowDialog();
MessageBox.Show(otherWindow.GetData());
}
}
}
Code for getting the data just before closing the window:
using System.Windows;
namespace GetDataFromOtherWindow
{
public partial class MainWindow : Window
{
private Window1? otherWindow;
public MainWindow()
{
InitializeComponent();
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
if (otherWindow != null)
{
MessageBox.Show(otherWindow.GetData());
}
base.OnClosing(e);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
otherWindow = new Window1();
otherWindow.Show();
}
}
}

Related

Navigate ContentControl from inside a UserControl in MVVM

I'm trying to create a sort of ShellView without using thirdparty frameworks, and I'm doing trying to do it via. ContentControls and UserControls.
I can navigate/switch the UserControls that is showed inside the ContentControls as long as the commands are fired from outside the UserControls, but nothing is happening when I move the code inside a button in a UserControl.
Currently I'm having one MainWindow.XAML, where I have one ContentControl.
This ContentControl is hosting either a LoginWindowUserControl, or a UserWindowUserControl - I want to be able switch the UserControl from within one of the UserControls.
My MainWindow.XAML looks like this:
<Window x:Class="ModelHealthApplication.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:vms="clr-namespace:ModelHealthApplication.ViewModels"
xmlns:ia="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:views="clr-namespace:ModelHealthApplication.Views.UserControls"
xmlns:local="clr-namespace:ModelHealthApplication"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<DataTemplate DataType="{x:Type vms:CurrentWindowUserStateViewModel}">
<views:UserView />
</DataTemplate>
<DataTemplate DataType="{x:Type vms:LoginWindowViewModel}">
<views:LoginView />
</DataTemplate>
<vms:NavigationViewModel x:Key="nVm" />
</Window.Resources>
<ia:Interaction.Triggers>
<ia:EventTrigger EventName="Loaded">
<ia:InvokeCommandAction Command="{Binding Source={StaticResource nVm}, Path=OpenLoginWindowCommand}" />
</ia:EventTrigger>
</ia:Interaction.Triggers>
<Grid DataContext="{StaticResource nVm}">
<DockPanel>
<Button Content="Test" DockPanel.Dock="Left" Command="{Binding OpenUserWindowStateCommand}" />
<ContentControl x:Name="WindowUserState" Content="{Binding CurrentWindowUserState}" />
</DockPanel>
</Grid>
And my UserWindowUserControl looks like this:
<UserControl x:Class="ModelHealthApplication.Views.UserControls.UserView"
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:vms="clr-namespace:ModelHealthApplication.ViewModels"
xmlns:views="clr-namespace:ModelHealthApplication.Views.UserControls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ModelHealthApplication.Views.UserControls"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<UserControl.Resources>
<DataTemplate DataType="{x:Type vms:MyModelsViewModel}">
<views:MyModelsView/>
</DataTemplate>
<DataTemplate DataType="{x:Type vms:MyAccountViewModel}">
<views:MyAccountView />
</DataTemplate>
<vms:NavigationViewModel x:Key="nVm" />
</UserControl.Resources>
<Grid>
<DockPanel DataContext="{StaticResource nVm}">
<Grid DockPanel.Dock="Top" Background="{StaticResource MainBlue}" Height="25">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal" Grid.Column="0">
<Button Content="My Models"
HorizontalAlignment="Center"
Command="{Binding OpenMyModelsCommand}"
Style="{StaticResource NavButtonStyle}"/>
<Button Content="My Account"
HorizontalAlignment="Center"
Command="{Binding OpenMyAccountCommand}"
Style="{StaticResource NavButtonStyle}"
/>
</StackPanel>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Right" Grid.Column="1" Margin="0, 0, 10, 0">
<TextBlock VerticalAlignment="Center" Foreground="White">
<Run Text="Logged in as:" FontWeight="Bold"/>
<Run Text="{Binding LoggedInAs}" d:Text="TestUser" />
</TextBlock>
<TextBlock Margin="20, 0 ,0 ,0" Text="Log Out" VerticalAlignment="Center" TextDecorations="Underline" Foreground="{StaticResource ComplenetarySecondOrange}" Background="{DynamicResource MainBlue}" Cursor="Hand">
<TextBlock.InputBindings>
<MouseBinding Command="{Binding OpenLoginWindowCommand}" MouseAction="LeftClick" />
</TextBlock.InputBindings>
</TextBlock>
</StackPanel>
</Grid>
<ContentControl x:Name="Pages" Content="{Binding SelectedViewModel}" />
</DockPanel>
</Grid>
</UserControl>
When I press the "Log Out" button/textblock I want to navigate back to the login window, but I can only do this from buttons that exist outside the UserControl.
I've read several other post similar to this, but I haven't found a solution that fits my needs - I tried using RelativeSource but without success - maybe someone can see what I'm doing wrong.
I'm using a "NavigationViewModel" to hold the commands which as I mentioned, works fine outside the UserControls:
using ModelHealthApplication.Commands;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace ModelHealthApplication.ViewModels
{
public class NavigationViewModel : INotifyPropertyChanged
{
public ICommand OpenMyModelsCommand { get; set; }
public ICommand OpenMyAccountCommand { get; set; }
public ICommand OpenUserWindowStateCommand { get; set; }
public ICommand OpenLoginWindowCommand { get; set; }
private object currentWindowUserState;
public object CurrentWindowUserState
{
get { return currentWindowUserState; }
set
{
currentWindowUserState = value;
OnPropertyChanged("CurrentWindowUserState");
}
}
private object selectedViewModel;
public object SelectedViewModel
{
get { return selectedViewModel; }
set
{
selectedViewModel = value;
OnPropertyChanged("SelectedViewModel");
}
}
public NavigationViewModel()
{
OpenMyModelsCommand = new OpenMyModelsCommand(this);
OpenMyAccountCommand = new OpenAccountCommand(this);
OpenUserWindowStateCommand = new OpenUserWindowStateCommand(this);
OpenLoginWindowCommand = new OpenLoginWindowCommand(this);
}
public void OpenUserWindowState(object obj)
{
CurrentWindowUserState = new CurrentWindowUserStateViewModel();
}
public void OpenLoginWindow(object obj)
{
CurrentWindowUserState = new LoginWindowViewModel();
}
public void OpenMyModels(object obj)
{
SelectedViewModel = new MyModelsViewModel();
}
public void OpenMyAccount(object obj)
{
SelectedViewModel = new MyAccountViewModel();
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
}
Ended up solving this with a great tutorial from SingletonSean on Youtube.
Posting here if anyone comes across this, and has the same issue.
Singleton Sean MVVM Navigatoin

Dynamic MenuItems with ItemsSource in xaml?

I'm crap atn english, so sorry..
I'm trying to create dynamic menu items that display something based on a collection (a list of object), here is my xaml, you can see the "ListBox" and the "MenuItem".
As I said, I'm binding the header to the "name" of my object :
MainWindow.xaml
<Grid Margin="0,0,-8,-9" Background="Black" >
<DockPanel x:Name="LayoutRoot">
<Grid VerticalAlignment="Top">
<MediaElement x:Name="mediaElement" HorizontalAlignment="Center" Margin="0,0,60,30" VerticalAlignment="Top" MouseLeftButtonUp="mediaElement_MouseLeftButtonUp">
</MediaElement>
<Menu HorizontalAlignment="Left" Height="30" VerticalAlignment="Top" Width="525" IsMainMenu="True">
<MenuItem Header="Menu">
<ListBox x:Name="myList" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="461,-261,-1,106" Background="#FFFFE800" MouseDoubleClick="ListBox_Double_Click" Width="57">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<MenuItem Header="{Binding name}"> </MenuItem>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</MenuItem>
</Menu>
</Grid>
Here is my code in the c#, as you can see I bind "myList" (which is my ListBox) with the ItemsGetSource of list (which contains the things I want to display in my menu):
public MainWindow()
{
var list = new List<History>
{
new History() { name = "Guy1"},
new History() { name = "Guy2"},
new History() { name = "Guy3"},
new History() { name = "Guy4"},
};
InitializeComponent();
this.myList.ItemsSource = list;
}
And my class "History" (the "name" field is what I want to display)
namespace MediaPlayer
{
public class History
{
// "prop" puis "tab"
public String name { get; set; }
public String path { get; set; }
public int time { get; set; }
public override string ToString()
{
return name;
}
}
}
I think I can't use itemSource for my menuItems, maybe?
Here is an example that only uses MenuItems:
MainWindow.xaml
<Grid Margin="0,0,-8,-9" Background="Black" >
<DockPanel x:Name="LayoutRoot">
<Grid VerticalAlignment="Top">
<MediaElement x:Name="mediaElement" HorizontalAlignment="Center" Margin="0,0,60,30" VerticalAlignment="Top" MouseLeftButtonUp="mediaElement_MouseLeftButtonUp">
</MediaElement>
<Menu HorizontalAlignment="Left" Height="30" VerticalAlignment="Top" Width="525" IsMainMenu="True">
<MenuItem Header="Menu" x:Name="myList">
<MenuItem.ItemContainerStyle>
<Style>
<Setter Property="MenuItem.Header" Value="{Binding name}"/>
</Style>
</MenuItem.ItemContainerStyle>
</MenuItem>
</Menu>
</Grid>
</DockPanel>
</Grid>
The result looks like this:

how to make user control return its item?

I have a user control with a canvas on it. I want to be able to reference the canvas element, but I can't.
I tried to create a method in the code-behind to return the canvas, but it doesn't work, because when I need to use it I must create a new instance of the user control and that will contain an empty canvas. I need the canvas that's in the current showing window.
Here is the method that I have created to return the canvas:
public DesignerCanvas ret()
{
return this.MyDesigner;
}
Here is the XAML:
<UserControl x:Class="DiagramDesigner.WindowsUserControl"
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:s="clr-namespace:DiagramDesigner"
xmlns:usercontrols="clr-namespace:DiagramDesigner"
xmlns:c="clr-namespace:DiagramDesigner.Controls"
mc:Ignorable="d"
d:DesignHeight="700" d:DesignWidth="1000">
<UserControl.Resources>
<ContextMenu x:Key="DesignerCanvasContextMenu" >
<MenuItem Header="Paste" Command="{x:Static ApplicationCommands.Paste}">
<MenuItem.Icon>
<Image Source="Resources/Images/Paste.png" Width="16"/>
</MenuItem.Icon>
</MenuItem>
<MenuItem Header="Select All" Command="{x:Static s:DesignerCanvas.SelectAll}"/>
</ContextMenu>
</UserControl.Resources>
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="1" Margin="0,10,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<!-- Toolbox -->
<StackPanel Grid.Column="0" Margin="0,0,5,0" >
<usercontrols:UserControl1></usercontrols:UserControl1>
</StackPanel>
<!-- GridSplitter -->
<GridSplitter Focusable="False" Width="2" Background="LightGray"
VerticalAlignment="Stretch" HorizontalAlignment="Right"/>
<!-- Designer -->
<GroupBox Header="Diagram" Grid.Column="1" Margin="3,0,0,0">
<ScrollViewer HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto">
<s:DesignerCanvas Focusable="true" x:Name="MyDesigner"
Background="{StaticResource WindowBackgroundBrush}"
Margin="10" FocusVisualStyle="{x:Null}"
ContextMenu="{StaticResource DesignerCanvasContextMenu}"/>
</ScrollViewer>
</GroupBox>
</Grid>
</Grid>
</UserControl>
and here is my usercontrol.xaml.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace DiagramDesigner
{
/// <summary>
/// Interaction logic for WindowsUserControl.xaml
/// </summary>
public partial class WindowsUserControl : UserControl
{
public WindowsUserControl()
{
InitializeComponent();
}
public DesignerCanvas ret()
{
return this.MyDesigner;
}
}
}
the mainwindow.xaml code
<Window x:Class="DiagramDesigner.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:DiagramDesigner"
xmlns:c="clr-namespace:DiagramDesigner.Controls"
xmlns:usercontrols="clr-namespace:DiagramDesigner"
WindowStartupLocation="CenterScreen" WindowState="Maximized"
Title="GEN Diagram Designer"
Height="700" Width="1000" Icon="Resources/Images/coollogo_com-61024358.png">
<Window.Resources>
<ContextMenu x:Key="DesignerCanvasContextMenu">
<MenuItem Header="Paste" Command="{x:Static ApplicationCommands.Paste}">
<MenuItem.Icon>
<Image Source="Resources/Images/Paste.png" Width="16"/>
</MenuItem.Icon>
</MenuItem>
<MenuItem Header="Select All" Command="{x:Static s:DesignerCanvas.SelectAll}"/>
</ContextMenu>
</Window.Resources>
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ContentControl Content="{StaticResource MyToolbar}"/>
<Button Margin="776.346,40.022,75.653,39.977" Click="Button_Click_1" Width="120" Height="40" >Generate Code</Button>
<Grid Grid.Row="1">
<usercontrols:WindowsUserControl Loaded="WindowsUserControl_Loaded">
</usercontrols:WindowsUserControl>
</Grid>
</Grid>
</Window>
my mainwindow.xaml.cs code
using System.Windows;
using System.Collections.Generic;
using System.Xml;
using System.Linq;
namespace DiagramDesigner
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
XmlDocument doc = new XmlDocument();
XmlElement elem = doc.CreateElement("code");
doc.AppendChild(elem);
List<DesignerItem> L = new List<DesignerItem>();
foreach (DesignerItem d in ***)
{
L.Add(d);
}
var orderedItems = L.OrderBy(item => DesignerCanvas.GetTop(item)).ToList();
foreach (DesignerItem d in orderedItems)
{
XmlNode ChildNode = doc.ImportNode(d.s.code(), true);
doc.FirstChild.AppendChild(ChildNode);
}
doc.Save(#"D:\code.xml");
}
private void WindowsUserControl_Loaded(object sender, RoutedEventArgs e)
{
}
}
}
in the mainwindow.xaml.cs
the first for each * here where i want to get my canvas
Give your control a name:
<usercontrols:WindowsUserControl Loaded="WindowsUserControl_Loaded" x:Name="someName" />
Then just reference the control using that name:
private void WindowsUserControl_Loaded(object sender, RoutedEventArgs e)
{
var theCanvasFromTheUserControl = someName.ret();
// now do something with theCanvasFromTheUserControl
}

Scope of menu shortcut key

When I click menu strip and then press shortcut key it works but it does not work otherwise. Is there something to set scope of shortcut key?
XAML:
<Window x:Class="NewGUI_WPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:common="clr-namespace:Common;assembly=RecentFileListLib"
Title="Sezor" Height="Auto" Width="Auto" WindowStartupLocation="Manual" Icon="/NewGUI_WPF;component/Images/i161.ICO" WindowStyle="SingleBorderWindow" Focusable="False" ResizeMode="CanResize" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" d:DesignHeight="243" d:DesignWidth="314" SizeToContent="Manual" WindowState="Maximized">
<Window.CommandBindings>
<CommandBinding Command="Save" Executed="SaveCommand" />
<CommandBinding Command="Open" Executed="OpenCommand" />
</Window.CommandBindings>
<Grid>
<Menu Height="23" Name="main_menu" VerticalAlignment="Top" HorizontalAlignment="Stretch" IsMainMenu="True">
<MenuItem Name="MI_Case" Header="Case">
<MenuItem Header="Open" Command="Open">
<MenuItem.Icon>
<Image Height="16" Width="16" Source="/NewGUI_WPF;component/Images/openHS.png" />
</MenuItem.Icon>
</MenuItem>
<MenuItem Header="Save" Name="MainMenu_File_Save" Command="Save">
<MenuItem.Icon>
<Image Height="16" Width="16" Source="/NewGUI_WPF;component/Images/saveHS.png" />
</MenuItem.Icon>
</MenuItem>
<MenuItem Header="Save as" Name="MainMenu_File_SaveAs" Click="MainMenu_File_SaveAs_Click" />
<common:RecentFileList x:Name="RecentFileList" />
<MenuItem Header="Quit" Click="MainMenu_File_Quit_Click" />
</MenuItem>
<MenuItem Header="View">
<MenuItem Header="Input File" Click="MainMenu_View_InputFile_Click" />
<MenuItem Header="Mesh File" Click="MainMenu_View_meshFile_Click" />
<MenuItem Name="MainMenu_View_Summary" Header="Summary" Click="MainMenu_View_summary_Click" />
</MenuItem>
<MenuItem Header="Define" >
<MenuItem Header="Input File" Click="MainMenu_Define_InputFile_Click" Name="MainMenu_Define_InputFile" />
<MenuItem Header="Mesh File" Click="MainMenu_Define_MeshFile_Click" Name="MainMenu_Define_MeshFile" />
<MenuItem Header="Simulation File" Click="MainMenu_Define_SimulFile_Click" Name="MainMenu_Define_SimulFile" />
<MenuItem Header="Boundaries" Click="MainMenu_Define_BC_Click" />
<MenuItem Header="Initials" Click="MainMenu_Define_Initials_Click" />
<MenuItem Header="Spatial Discretization" Click="MainMenu_Define_SpatDis_Click" />
<MenuItem Header="Flow" Click="MainMenu_Define_Flow_Click" />
<MenuItem Header="Material" Click="MainMenu_Define_Material" />
<MenuItem Header="Algoritm" Click="MainMenu_Define_Algoritm" />
<MenuItem Header="Gradient Reconstruction">
<RadioButton Content="Least-Squares" Checked="Least_Squares_Checked" Name="rad_GR_LS" />
<RadioButton Content="Green-Gauss" Click="Green_Gauss_Checked" Name="rad_GR_GG" />
</MenuItem>
</MenuItem>
<MenuItem Header="Run" >
<MenuItem Header="Simulation" Click="MainMenu_Run_Simulation_Click" />
</MenuItem>
</Menu>
<Frame Height="Auto" HorizontalAlignment="Left" Margin="40,60,30,20" Name="frm_summary" VerticalAlignment="Top" Width="Auto" NavigationUIVisibility="Hidden" />
<StatusBar Height="23" Name="statusBar1" VerticalAlignment="Bottom" Margin="0">
<TextBlock Name="statBar_text_1"></TextBlock>
</StatusBar>
</Grid>
Code:
private void OpenCommand(object sender, ExecutedRoutedEventArgs e) {...}
private void SaveCommand(object sender, ExecutedRoutedEventArgs e) {...}
Remove Focusable="False" in your Window tag.
Looks like you need to add CanExecute to the CommandBinding and a corresponding code behind method.
Here's a minimal demonstration that wires up Control-S to launch the Help command.
The XAML:
<Window x:Class="stackoverflow___scope_of_menu_shortcut_key.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">
<Window.CommandBindings>
<CommandBinding Command="Help" CanExecute="HelpCanExecute" Executed="HelpExecuted"/>
</Window.CommandBindings>
<Window.InputBindings>
<KeyBinding Command="Help" Key="S" Modifiers="Control"/>
</Window.InputBindings>
<Menu>
<MenuItem Header="File">
<MenuItem Header="Help" Name="HelpMenu" Command="Help"/>
</MenuItem>
</Menu>
</Window>
The code behind:
using System.Windows;
using System.Windows.Input;
namespace stackoverflow___scope_of_menu_shortcut_key
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void HelpCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void HelpExecuted(object sender, ExecutedRoutedEventArgs e)
{
System.Diagnostics.Process.Start("http://www.microsoft.com");
}
}
}
Notice that if you comment out the line:
e.CanExecute = true;
the key bindings no longer function.
Here's your example, stripped down to a bare minimum. This works on my system:
XAML:
<Window x:Class="stackoverflow___scope_of_menu_shortcut_key.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">
<Window.CommandBindings>
<CommandBinding Command="Save" Executed="MyCommand" />
</Window.CommandBindings>
<MenuItem Header="Save" Command="ApplicationCommands.Save"/>
</Window>
Code behind:
using System.Windows;
using System.Windows.Input;
namespace stackoverflow___scope_of_menu_shortcut_key
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void MyCommand(object sender, ExecutedRoutedEventArgs e)
{
System.Diagnostics.Process.Start("http://www.microsoft.com");
}
}
}

Click Event in Silverlight User Control

I have user control in Silverlight which has a button click event. When I add that user control to a page, the click event does not fire. Is there something else I need to do?
Update
The user control by itself fires the click event. When inside the page, it does not
Page
<navigation:Page x:Class="RadControlsSilverlightApp2.Page1"
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"
mc:Ignorable="d"
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
d:DesignWidth="640" d:DesignHeight="480"
Title="Page1 Page" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
xmlns:my1="clr-namespace:TestSilverLight.UserControls;assembly=TestSilverLight">
<Grid x:Name="LayoutRoot">
<sdk:Label Height="28" HorizontalAlignment="Left" Margin="101,38,0,0" Name="label1" VerticalAlignment="Top" Width="120" Content="Test page" />
<my1:Top10Programs HorizontalAlignment="Left" Margin="335,71,0,0" Name="top10Programs1" VerticalAlignment="Top" />
</Grid>
User control
<UserControl x:Class="RadControlsSilverlightApp2.MainPage"
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:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480" BorderThickness="1" xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation">
Have you raised an event in the usercontrol that is handled in the main page?
UserControl XAML
<Grid x:Name="LayoutRoot" Background="White" Height="133">
<sdk:Label Height="18" HorizontalAlignment="Left" Margin="12,31,0,0" Name="label1" VerticalAlignment="Top" Width="58" Content="Name" />
<sdk:Label Content="Password" Height="18" HorizontalAlignment="Left" Margin="12,60,0,0" Name="label2" VerticalAlignment="Top" Width="58" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="89,27,0,0" Name="textBox1" VerticalAlignment="Top" Width="253" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="89,55,0,0" Name="textBox2" VerticalAlignment="Top" Width="253" />
<Button Content="Login" Height="23" HorizontalAlignment="Left" Margin="161,101,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>
UserControl code behind
public class userNameEventArgs : EventArgs
{
public string userName{get;set;}
}
public partial class LoginBox : UserControl
{
public event EventHandler<userNameEventArgs> LoggedIn;
public LoginBox()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
LoggedIn(this, new userNameEventArgs(){userName=textBox1.Text});
}
}
Mainpage XAML
<Grid x:Name="LayoutRoot" Background="White">
<Button Content="Main Page" Height="23" HorizontalAlignment="Left" Margin="36,50,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
<local:LoginBox Margin="100,122,179,223" LoggedIn="LoginBox_LoggedIn" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="36,376,0,0" Name="textBlock1" Text="TextBlock" VerticalAlignment="Top" Width="94" />
</Grid>
Mainpage codebehind
public partial class MainPage : UserControl
{
public MainPage()
{
// Required to initialize variables
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Mainpage pressed!!");
}
private void LoginBox_LoggedIn(object sender, userNameEventArgs e)
{
textBlock1.Text = e.userName;
}
}
This allows the text block on the main page to be updated when the button on the user control is clicked. It raises an event that is handled on the mainpage. The EventArgs tranfers the information between the user control and the mainpage.
Hope this helps.

Categories

Resources