button will be Visible if another window loaded - c#

i have project where i want button in the MainWindow to be Visible if another window is loaded and Collapsed if this window is close
i have try in this way
Xaml for MainWindow
<Grid >
<Button x:Name="button" Content="Opne Window1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Click="button_Click" Margin="220,110,0,0"/>
<Button x:Name="WinBut1" Content="Check order" HorizontalAlignment="Left" VerticalAlignment="Top" Visibility="Hidden" Width="75" Click="button9_Click" Margin="10,1,0,0"/>
</Grid>
in the codebehind of the MainWindow control:
public partial class MainWindow : Window
{
Window1 Window1 = new Window1();
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
//this.Window1.Loaded += new RoutedEventHandler (CheckWindow);
this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Window1 childWindow = new Window1();
childWindow.MyEvent += new EventHandler(childWindow_MyEvent);
childWindow.ShowDialog();
}
void childWindow_MyEvent(object sender, EventArgs e)
{
if (Window1 != null)
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(
delegate ()
{
WinBut1.Visibility = Visibility.Visible;
}
));
}
}
//void CheckWindow(object sender, RoutedEventArgs e)
//{
// if (Window1 != null && Window1.Visibility == Visibility.Visible)
// {
// Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(
// delegate ()
// {
// WinBut1.Visibility = Visibility.Visible;
// }
// ));
// }
//}
private void button_Click(object sender, RoutedEventArgs e)
{
new Window1().Show();
}
}
in the codebehind of the Window1 control:
public Window1()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(win1_Loaded);
}
public event EventHandler MyEvent;
protected void OnMyEvent()
{
if (this.MyEvent != null)
this.MyEvent(this, EventArgs.Empty);
}
void win1_Loaded(object sender, RoutedEventArgs e)
{
this.OnMyEvent();
}
}

Well , there are tow events Loaded and Closed in Window class object.
You need to subscribe two events handler to them. All is done in your Window class.
Well based on your requirment you can do the following:
private void Button_Click(object sender, RoutedEventArgs e)
{
Window1 win = new Window1();
win.Loaded += win_Loaded;
win.Closed += win_Closed;
win.ShowDialog();
}
void win_Closed(object sender, EventArgs e)
{
this.but.Visibility = Visibility.Visible;
}
void win_Loaded(object sender, RoutedEventArgs e)
{
this.but.Visibility = Visibility.Hidden;
}
Well this code is used in your window code behind.

It's quite simple you only need to the IsVisibleChanged of Window1 in your MainWindow and set visibility of your button to the visibility of your window1.
Your MainWindow.cs:
public partial class MainWindow : Window
{
Window1 window1;
public MainWindow()
{
InitializeComponent();
window1 = new Window1();
window1.IsVisibleChanged += Window1_IsVisibleChanged;
this.Closing += MainWindow_Closing;
}
private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Application.Current.Shutdown();//will close all windows
}
private void Window1_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
buttonCollapsed.Visibility = window1.Visibility;
}
private void buttonShow_Click(object sender, RoutedEventArgs e)
{
window1.Show();
}
And Window1.cs:
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
this.Closing += Window1_Closing;
}
private void Window1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if(sender is Window1)
{
e.Cancel = true;//Cancel the closing
this.Hide();
}
}
private void buttonHide_Click(object sender, RoutedEventArgs e)
{
this.Hide();//hide your window --> IsVisibilityChanged-Event will be raised
}
}

Related

How can I change a "Frame Content" in another class? (C# WPF XAML)

once to explain, I open a xaml page via "frame.content" and in this page I have opened, I want to open another one but on the frame where the second page is running.
but i can't open the page,
nothing happens. not even an expection.
So here what I have written:
This is the class from the page that is open
private void bttn_start(object sender, RoutedEventArgs e)
{
MainWindow mw = new MainWindow();
mw.JoinNextPage();
}
This is the MainWindow class where the frame is.
public partial class MainWindow : Window
{
public void JoinNextPage() => pageMirror.Content = new page_finish();
}
You should use RoutedCommand to trigger the Frame navigation instead of the static MainWindow reference.
This removes the complete navigation logic (button event handlers) from your pages.
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public static RoutedCommand NextPageCommand { get; } = new RoutedCommand("NextPageCommand", typeof(MainWindow));
public MainWindow()
{
InitializeComponent();
CommandBindings.Add(
new CommandBinding(NextPageCommand, ExecuteNextPageCommand, CanExecuteNextPageCommand));
}
private void CanExecuteNextPageCommand(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void ExecuteNextPageCommand(object sender, ExecutedRoutedEventArgs e)
{
// Logic to select the next Frame content
JoinNextPage();
}
}
MainWindow.xaml
<Window>
<Frame>
<Frame.Content>
<Page>
<Button Command="{x:Static local:MainWindow.NextPageCommand}"
Content="Next Page" />
</Page>
</Frame.Content>
</Frame>
</Window>
Try this:
private void bttn_start(object sender, RoutedEventArgs e)
{
MainWindow mw = (MainWindow)Application.Current.MainWindow;
mw.JoinNextPage();
}

Use a webservice to get a random video and play it. C# WPF

I need help figuring out where to start on using a webservice to get a random video to play. This is the program instructions I am working on:
For this problem, you will be using a webservice to get a random video to play. The webservice can be found at : http://pcbstuou.w27.wh-2.com/webservices/3033/api/random/video . You will want to have a button to get a random video from the webservice for the user to press as well as a play and stop button. When the video is playing, the play button should double as a pause button and should change the text to reflect the available option.
This is what I have:
namespace Problem3
{
public partial class Media
{
private bool mediaPlayerIsPlaying = false;
public mePlayer;
private void Open_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void Open_Executed(object sender, ExecutedRoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Media files (*.mp3;*.mpg;*.mpeg)|*.mp3;*.mpg;*.mpeg|All files (*.*)|*.*";
if (openFileDialog.ShowDialog() == true)
mePlayer.Source = new Uri(openFileDialog.FileName);
}
private void Play_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = (mePlayer != null) && (mePlayer.Source != null);
}
private void Play_Executed(object sender, ExecutedRoutedEventArgs e)
{
mePlayer.Play();
mediaPlayerIsPlaying = true;
}
private void Stop_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = mediaPlayerIsPlaying;
}
private void Stop_Executed(object sender, ExecutedRoutedEventArgs e)
{
mePlayer.Stop();
mediaPlayerIsPlaying = false;
}
The meplayer is having an error and I obviously need to create a method for it, but what would the method include? Also, I am not sure if I even went about this right?
This is the Main:
namespace Problem3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Search_button_Click(object sender, RoutedEventArgs e, object mediaElement)
{
//var FullVimeoUrl = "http://pcbstuou.w27.wh-2.com/webservices/3033/api/random/video ";
//mediaElement.Source = new Uri(FullVimeoUrl.ToString(), UriKind.RelativeOrAbsolute);
//mediaElement.Play();
}
private void Search_button_Click(object sender, RoutedEventArgs e)
{
var FullVimeoUrl = "http://pcbstuou.w27.wh-2.com/webservices/3033/api/random/video ";
mediaElement.Source = new Uri(FullVimeoUrl.ToString(), UriKind.RelativeOrAbsolute);
mediaElement.Play();
}
public void VideoPath(object sender, RoutedEventArgs e)
{
}
private class mediaElement
{
public static Uri Source { get; internal set; }
}
//public string Play()
//{
//}
private void Play_Click(object sender, RoutedEventArgs e)
{
//void OnMouseDownPauseMedia(object sender, MouseButtonEventArgs args)
//{
// // The Pause method pauses the media if it is currently running.
// // The Play method can be used to resume.
// mediaElement.Pause();
//}
}
private void Stop_Click(object sender, RoutedEventArgs e)
{
}
}
I am sure I have myself all mixed up because I have been working on this entirely too long. I am at the point of way overthinking!
Please try this code, To Use a webservice to get a random video and play it. C# WPF
XAML file:
<Window x:Class="WpfTutorialSamples.Audio_and_Video.MediaPlayerVideoControlSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MediaPlayerVideoControlSample" Height="300" Width="300">
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<MediaElement Source="http://hubblesource.stsci.edu/sources/video/clips/details/images/hst_1.mpg" LoadedBehavior="Manual" Name="mePlayer" />
<StackPanel Grid.Row="1">
<Label Name="lblStatus" Content="Not playing..." HorizontalContentAlignment="Center" Margin="5" />
<WrapPanel HorizontalAlignment="Center">
<Button Name="btnPlay" Click="btnPlay_Click">Play</Button>
<Button Name="btnPause" Margin="5,0" Click="btnPause_Click">Pause</Button>
<Button Name="btnStop" Click="btnStop_Click">Stop</Button>
</WrapPanel>
</StackPanel>
</Grid>
</Window>
Class File:
using System;
using System.Windows;
using System.Windows.Threading;
namespace WpfTutorialSamples.Audio_and_Video
{
public partial class MediaPlayerVideoControlSample : Window
{
public MediaPlayerVideoControlSample()
{
InitializeComponent();
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += timer_Tick;
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
if(mePlayer.Source != null)
{
if(mePlayer.NaturalDuration.HasTimeSpan)
lblStatus.Content = String.Format("{0} / {1}", mePlayer.Position.ToString(#"mm\:ss"), mePlayer.NaturalDuration.TimeSpan.ToString(#"mm\:ss"));
}
else
lblStatus.Content = "No file selected...";
}
private void btnPlay_Click(object sender, RoutedEventArgs e)
{
mePlayer.Play();
}
private void btnPause_Click(object sender, RoutedEventArgs e)
{
mePlayer.Pause();
}
private void btnStop_Click(object sender, RoutedEventArgs e)
{
mePlayer.Stop();
}
}
}
I hope this code will be useful for you.
Thank you.

How to fill ContextMenuStrip in XAML?

I've created WPF application with NotifyIcon to work in tray.
public partial class MainWindow : Window
{
public NotifyIcon NotifyIcon { get; } = new NotifyIcon
{
Icon = Properties.Resources.status_on_ico,
Visible = true
};
public MainWindow()
{
InitializeComponent();
NotifyIcon.ContextMenuStrip = MyContextMenuStrip;
NotifyIcon.Click += NotifyIcon_Click;
}
private void Window_Closing(object sender, CancelEventArgs e)
{
e.Cancel = true;
WindowState = WindowState.Minimized;
}
private void NotifyIcon_Click(object sender, EventArgs e)
{
Show();
}
}
XAML of main window is nothing special and not relevant.
I want to create ContextMenuStrip of NotifyIcon in XAML (I know how to do it code behind but don't want it).
Here is what I've managed.
<WindowsFormsHost>
<wf:ContextMenuStrip x:Name="MyContextMenuStrip" TopLevel="False">
<wf:ContextMenuStrip.Items>
<!-- How to add items here? -->
</wf:ContextMenuStrip.Items>
</wf:ContextMenuStrip>
</WindowsFormsHost>
The question is how to add items to ContextMenuStrip.Items with Name and Click event handlers in XAML?
The question is how to add items to ContextMenuStrip.Items with Name and Click event handlers in XAML?
Try this:
<WindowsFormsHost>
<wf:ContextMenuStrip x:Name="MyContextMenuStrip" TopLevel="False">
<wf:ContextMenuStrip.Items>
<wf:ToolStripMenuItem Text="test1" Click="It_Click" />
<wf:ToolStripMenuItem Text="test2" />
</wf:ContextMenuStrip.Items>
</wf:ContextMenuStrip>
</WindowsFormsHost>
private void It_Click(object sender, EventArgs e)
{
MessageBox.Show("click!");
}

How to transfer control from one control to another

I created next WPF controls : Window1, View, Edit in different files:
In MainWindow.xaml MainWindow contein two ContentControls
<Grid>
<ContentControl x:Name="Viewer" Content="ContentControl1" DockPanel.Dock="Top" Height="Auto" RenderTransformOrigin="0.5,0.5">
</ContentControl>
<ContentControl x:Name="Editor" Content="ContentControl2" DockPanel.Dock="Top" Height="Auto" VerticalAlignment="Bottom" RenderTransformOrigin="0.5,0.5" Visibility="Hidden"/>
</Grid>
This is part of .cs file:
public partial class MainWindow : Window
{
View v = new View();
Edit e = new Edit();
public MainWindow()
{
InitializeComponent();
Window1.Viewer.Content = v;
Window1.Editor.Content = e;
}
public void swichToEditor()
{
Window1.Editor.Visibility = System.Windows.Visibility.Visible;
Window1.Viewer.Visibility = System.Windows.Visibility.Hidden;
}
public void swichToViewer()
{
Window1.Ediort.Visibility = System.Windows.Visibility.Hidden;
Window1.Viewer.Visibility = System.Windows.Visibility.Visible;
}
}
ComtentControl1 with x:name=Editor contain this userControl:
public partial class Edit : UserControl
{
public Edit()
{
this.InitializeComponent();
}
private void Button1_Click(object sender, System.Windows.RoutedEventArgs e)
{
// TODO: Add event handler implementation here.
}
}
ComtentControl2 with x:name=Viewer contain this userControl:
public partial class View : UserControl
{
public View()
{
this.InitializeComponent();
}
private void Button2_Click(object sender, System.Windows.RoutedEventArgs e)
{
// TODO: Add event handler implementation here.
}
}
When button1 will be pressed i need that Editor will be hide and Viewer will be visible. and vice-versa
I know better c++ syntax. and signal-slot method closer to me :)
What your advice to me?
You can use the RoutedEvent's behavior. You just need to register your Window to the Click RoutedEvent. Take a look:
public partial class MainWindow : Window
{
View v = new View();
Edit e = new Edit();
public MainWindow()
{
InitializeComponent();
Window1.Viewer.Content = v;
Window1.Editor.Content = e;
EventManager.RegisterClassHandler(GetType(), Button.ClickEvent, new RoutedEventHandler(OnButtonClick));
}
private void OnButtonClick(object sender, RoutedEventArgs e)
{
if (e.Source is View)
{
SwichToEditor();
}
else
{
SwichToViewer();
}
}
public void SwichToEditor()
{
Window1.Editor.Visibility = System.Windows.Visibility.Visible;
Window1.Viewer.Visibility = System.Windows.Visibility.Hidden;
}
public void SwichToViewer()
{
Window1.Ediort.Visibility = System.Windows.Visibility.Hidden;
Window1.Viewer.Visibility = System.Windows.Visibility.Visible;
}
}
Then you do not need to have a button click event handler in your UserControls.
I hope this sample can help you.

Close Window without code-behind in WPF

Is it possible to bind a Button to Close the Window without adding a code-behind event?
<Button Content="OK" Command="{Binding CloseWithSomeKindOfTrick}" />
Instead of the following XAML:
<Button Content="OK" Margin="0,8,0,0" Click="Button_Click">
With the code-behind:
private void Button_Click(object sender, RoutedEventArgs e)
{
Close();
}
Thanks!
If you want close the dialog Window, you can add for Button IsCancel property:
<Button Name="CloseButton"
IsCancel="True" ... />
This means the following MSDN:
When you set the IsCancel property of a Button to true, you create a Button that is registered with the AccessKeyManager. The button is then activated when a user presses the ESC key.
Now, if you click on this Button, or press Esc then dialog Window is closing, but it does not work for the normal MainWindow.
To close the MainWindow, you can simply add a Click handler which has already been shown. But if you want a more elegant solution that would satisfy the MVVM style you can add the attached behavior:
public static class ButtonBehavior
{
#region Private Section
private static Window MainWindow = Application.Current.MainWindow;
#endregion
#region IsCloseProperty
public static readonly DependencyProperty IsCloseProperty;
public static void SetIsClose(DependencyObject DepObject, bool value)
{
DepObject.SetValue(IsCloseProperty, value);
}
public static bool GetIsClose(DependencyObject DepObject)
{
return (bool)DepObject.GetValue(IsCloseProperty);
}
static ButtonBehavior()
{
IsCloseProperty = DependencyProperty.RegisterAttached("IsClose",
typeof(bool),
typeof(ButtonBehavior),
new UIPropertyMetadata(false, IsCloseTurn));
}
#endregion
private static void IsCloseTurn(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue is bool && ((bool)e.NewValue) == true)
{
if (MainWindow != null)
MainWindow.PreviewKeyDown += new KeyEventHandler(MainWindow_PreviewKeyDown);
var button = sender as Button;
if (button != null)
button.Click += new RoutedEventHandler(button_Click);
}
}
private static void button_Click(object sender, RoutedEventArgs e)
{
MainWindow.Close();
}
private static void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
MainWindow.Close();
}
}
And in MainWindow use this Behavior like as:
<Window x:Class="MyProjectNamespace.MainWindow"
xmlns:local="clr-namespace:MyProjectNamespace">
<Button Name="CloseButton"
local:ButtonBehavior.IsClose="True" ... />

Categories

Resources