How can i share an UDP Client betwen Methodes in WPF? - wpf

Im am kinda new to coding and had a question. When I open up a UDP-CLient by an button clic,k and try to access it from another Method, I just get the Error: The name "server" does not exist in current context.
The name "connected" does not exist in current context.
When I am connected to the server, I dont want to close the connection,and open it up again.
How Can I fix it?What am I missing? Looking forward for help!
I think it is the same problem with the boolean, it doesnt work either.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
using System.Net;
using System.Net.Sockets;
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
UdpClient server = new UdpClient();
Boolean connected = false;
}
public void connect_btn_Click(object sender, RoutedEventArgs e)
{
try
{
UdpClient server = new UdpClient(ip_box.Text, Convert.ToInt32(port_box.Text));
Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");
server.Send(sendBytes, sendBytes.Length);
connected = true;
}
catch { }
}
public void ip_box_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void port_box_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void send_data_btn_Click(object sender, RoutedEventArgs e)
{
Byte[] sendBytes = Encoding.ASCII.GetBytes("Test");
server.Send(sendBytes, sendBytes.Length);
}
}
}

Related

Record Mouse clicks and display on the button itself using WPF

I have a button. Each and every time the user clicks that button Message should be displayed on the button "1" 2nd time when the user clicks the button, it should display "2" and so on.
How do i do it?
enter code here
I have to do it using WPF.
If you are using MVVM then create an property in Viewmodel and set default value 1 and also use Icommand for handle click event of Button.
In ViewModel when you click on button then increase or change the value of your property.
In XAML bind Content property of button to ViewModel's property.
I think this is just what you needed!
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 WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
button1.Content = null;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
if (button1.Content==null)
{
button1.Content = 1;
}
else
{
button1.Content = (Int32.Parse(button1.Content.ToString()) + 1).ToString();
}
}
}
}

Checking if a method is attached to an event

Is there a way in WPF to check if an event has a method attached to it?
I'd like to be able to do something like
if (MyEvent != Null)
{
...
}
Since you are creating your own event, it is possible to check if a method is attached to it or not.
Below I have defined a method IsMethodAttachedToMyEvent which will check if the given Action is attached to MyEvent or not. I have used the GetInvocationList() method of MyEvent to loop through the attached methods.
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;
using System.ComponentModel;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public event Action MyEvent;
public MainWindow()
{
InitializeComponent();
MyEvent += new Action(MainWindow_MyEvent);
MessageBox.Show("Is MainWindow_MyEvent attached\n\n" + IsMethodAttachedToMyEvent(new Action(MainWindow_MyEvent) ));
MessageBox.Show("Is MainWindow_MyEvent_1 attached\n\n" + IsMethodAttachedToMyEvent(new Action(MainWindow_MyEvent_1)));
}
public bool IsMethodAttachedToMyEvent(Action methodToCheck)
{
if (MyEvent != null)
{
foreach (Action act in MyEvent.GetInvocationList())
{
if (act.Method == methodToCheck.Method)
{
return true;
}
}
}
return false;
}
void MainWindow_MyEvent()
{
throw new NotImplementedException();
}
void MainWindow_MyEvent_1()
{
throw new NotImplementedException();
}
}
}

WebBrowser in WPF using MVVM pattern

I am trying to open HTML file in WebBrowser window of WPF using MVVM patten.
Note: I have fixed the issues i was getting. Now this code works as desired.
ViewHTMLPageView.xaml
<Window x:Class="MyProject.ViewHTMLPageView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyProject.Utility"
Title="HTML Report" Height="454" Width="787"
>
<Grid Name="grid1">
<WebBrowser local:WebBrowserUtility.BindableSource="{Binding ReportPage}" />
</Grid>
</Window>
ViewHTMLPageViewModel.cs
namespace MyProject
{
public class ViewHTMLPageViewModel: ViewModelBase
{
public ViewHTMLPageView()
{
//Testing html page on load
_reportPage = "<table border='5'><tr><td> This is sample <b> bold </b></td></tr></table>";
OnPropertyChanged("ReportPage");
}
private string _reportPage;
public string ReportPage
{
get
{
return _reportPage;
}
set
{
if (_reportPage != value)
{
_reportPage = value;
OnPropertyChanged("ReportPage");
}
}
}
}
WebBrowserUtility.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
namespace MyProject.Utility
{
public static class WebBrowserUtility
{
public static readonly DependencyProperty BindableSourceProperty =
DependencyProperty.RegisterAttached("BindableSource", typeof(string),
typeof(WebBrowserUtility), new UIPropertyMetadata(null,
BindableSourcePropertyChanged));
public static string GetBindableSource(DependencyObject obj)
{
return (string)obj.GetValue(BindableSourceProperty);
}
public static void SetBindableSource(DependencyObject obj, string value)
{
obj.SetValue(BindableSourceProperty, value);
}
public static void BindableSourcePropertyChanged(DependencyObject o,
DependencyPropertyChangedEventArgs e)
{
var webBrowser = (WebBrowser)o;
webBrowser.NavigateToString((string)e.NewValue);
}
}
}
In WebBrowserUtility.cs, change the following statement:
using System.Windows.Forms;
to
using System.Windows.Controls;
Now, for +1 on your question, can you tell me why this fixes your problem?

WPF Multi-touch tracking touch points

I'm trying to do a simple application that, when a user touchs a screen, app creates simple point, ellipse, or sth 2d object, and when user moves his finger it should follow, but also when there is a scond touch at the same time new object also has to be created and do the same thing with respect to users movement. Whenever user fingersup, object will be deleted.
To do this, I'm trying to change the touchdrawing code from this link http://www.cookingwithxaml.com/recipes/wpf4/wpf4touch.zip but I couldn't figure out which method should I need to change ?
Can you give advice about that please ?
Thanks.
Here is some sample xaml/C# code that does what I think you want:
MainWindow.xaml:
<Window x:Class="MultitouchExperiments.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>
<Canvas
x:Name="TouchCanvas"
TouchDown="TouchCanvas_TouchDown" TouchUp="TouchCanvas_TouchUp"
TouchMove="TouchCanvas_TouchMove" TouchLeave="TouchCanvas_TouchLeave"
TouchEnter="TouchCanvas_TouchEnter"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
Background="Black"
IsManipulationEnabled="True" />
</Grid>
</Window>
MainWindow.xaml.cs:
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;
using System.Diagnostics;
namespace MultitouchExperiments
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Dictionary<TouchDevice, Ellipse> _Followers = new Dictionary<TouchDevice, Ellipse>();
public MainWindow()
{
InitializeComponent();
}
private void TouchCanvas_TouchDown(object sender, TouchEventArgs e)
{
TouchCanvas.CaptureTouch(e.TouchDevice);
Ellipse follower = new Ellipse();
follower.Width = follower.Height = 50;
follower.Fill = Brushes.White;
follower.Stroke = Brushes.White;
TouchPoint point = e.GetTouchPoint(TouchCanvas);
follower.RenderTransform = new TranslateTransform(point.Position.X, point.Position.Y);
_Followers[e.TouchDevice] = follower;
TouchCanvas.Children.Add(follower);
}
private void TouchCanvas_TouchUp(object sender, TouchEventArgs e)
{
TouchCanvas.ReleaseTouchCapture(e.TouchDevice);
TouchCanvas.Children.Remove(_Followers[e.TouchDevice]);
_Followers.Remove(e.TouchDevice);
}
private void TouchCanvas_TouchMove(object sender, TouchEventArgs e)
{
if (e.TouchDevice.Captured == TouchCanvas)
{
Ellipse follower = _Followers[e.TouchDevice];
TranslateTransform transform = follower.RenderTransform as TranslateTransform;
TouchPoint point = e.GetTouchPoint(TouchCanvas);
transform.X = point.Position.X;
transform.Y = point.Position.Y;
}
}
private void TouchCanvas_TouchLeave(object sender, TouchEventArgs e)
{
//Debug.WriteLine("leave " + e.TouchDevice.Id);
}
private void TouchCanvas_TouchEnter(object sender, TouchEventArgs e)
{
//Debug.WriteLine("enter " + e.TouchDevice.Id);
}
}
}

XAML page Flip twist

I have this Page.xaml
<UserControl x:Class="SLBookDemoApp.Page"
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SLMitsuControls;assembly=SLMitsuControls"
Width="800" Height="600" Loaded="UserControl_Loaded">
<Grid>
<local:UCBook x:Name="book" Margin="50" />
</Grid>
</UserControl>
And the correspondent Page.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SLMitsuControls;
namespace SLBookDemoApp
{
public partial class Page : UserControl, IDataProvider
{
public Page()
{
InitializeComponent();
}
private List<Grid> pages;
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
/*
pages = new List<Button>
{
new Button { Content = "Page 0"},
new Button { Content = "Page 1", Background = new SolidColorBrush(Colors.Green) },
new Button { Content = "Page 2", Background = new SolidColorBrush(Colors.Yellow) },
new Button { Content = "Page 3", Background = new SolidColorBrush(Colors.Brown) },
new Button { Content = "Page 4", Background = new SolidColorBrush(Colors.Magenta) },
new Button { Content = "Page 5", Background = new SolidColorBrush(Colors.Red) }
};
*/
System.Windows.Application.LoadComponent(this, new System.Uri("/SLBookDemoApp;PagTeste2.xaml", System.UriKind.Relative));
Grid LayoutRoot = ((Grid)(FindName("LayoutRoot")));
//TextBlock testTextBlock = ((TextBlock)(FindName("testTextBlock")));
pages = new List<Grid>
{
};
pages.Add(LayoutRoot);
/*
int i = 0;
foreach (var b in pages)
{
if (i % 2 == 0)
b.Click += Button_Click;
else
b.Click += Button_Click_1;
i++;
}
*/
book.SetData(this);
}
#region IDataProvider Members
public object GetItem(int index)
{
return pages[index];
}
public int GetCount()
{
return pages.Count;
}
#endregion
private void Button_Click(object sender, RoutedEventArgs e)
{
book.AnimateToNextPage(500);
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
book.AnimateToPreviousPage(500);
}
}
}
And the XAML I wnat to include is this PagTeste2.xaml
<Grid
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SLBookDemoApp.PagTeste2"
x:Name="LayoutRoot">
<Rectangle Width="192" Height="80" Fill="#FF8F0A0A" Stroke="#FF000000" Canvas.Left="224" Canvas.Top="104"/>
</Grid>
With the correspondent PagTeste2.xaml.cs
using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;
//using System.Windows.Navigation;
using SLMitsuControls;
namespace SLBookDemoApp
{
public partial class PagTeste2
{
public PagTeste2()
{
this.InitializeComponent();
// Insert code required on object creation below this point.
}
}
}
I am getting an error on this line
System.Windows.Application.LoadComponent(this, new System.Uri("/SLBookDemoApp;PagTeste2.xaml", System.UriKind.Relative));
Anyone knows why ?
Use this instead:
this.Content = new PagTeste2();
You only have to do any sort of assembly loading if you're loading content from a different assembly and even then you wouldn't use it to set content.
If you're actually asking how do you dynamically load an assembly, MS have an example of how.
You may want to try /SLBookDemoApp;component/PageTeste2.xaml.
If PagTeste2.xaml is at the top-level folder of your project you can load it using this code:
Application.LoadComponent(
this,
new System.Uri(
"/SLBookDemoApp;component/PagTeste2.xaml",
System.UriKind.Relative
)
);
If you have placed PagTeste2.xaml in a subfolder inside your project (say folder Tests) you need to include the path to the file in the uri:
Application.LoadComponent(
this,
new System.Uri(
"/SLBookDemoApp;component/Tests/PagTeste2.xaml",
System.UriKind.Relative
)
);
Also, pay close attention to spelling. PagTest2.xaml is different from PageTeste2.xaml and PageTest2.xaml. Apparently Test is inserted before the e in Page.
You can read more about pack URI's on MSDN.

Resources