C# WPF Getting error - System.InvalidOperationException: - c#

I have just started to learn windows application development using C# WPF, and we have been given self learn project to develop one windows application. I am trying to create the application to Chat Client-to-Client. I have created a class MainWindow.xaml and MainWindow.xaml.cs to handle that. When I call that class from main form I am getting the following error.
And these are the two classes:
<Window x:Class="Chat_Client.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:Chat_Client"
mc:Ignorable="d"
Title="Chat: Client-to-Client" Height="450" Width="625">
<Grid>
<Label x:Name="label" Content="IP" HorizontalAlignment="Left" Margin="39,52,0,0" VerticalAlignment="Top"/>
<Label x:Name="label1" Content="Port" HorizontalAlignment="Left" Margin="39,100,0,0" VerticalAlignment="Top"/>
<Label x:Name="label2" Content="IP" HorizontalAlignment="Left" Margin="287,59,0,0" VerticalAlignment="Top"/>
<Label x:Name="label3" Content="Port" HorizontalAlignment="Left" Margin="287,100,0,0" VerticalAlignment="Top" RenderTransformOrigin="-0.037,-0.343"/>
<TextBox x:Name="textLocalIp" HorizontalAlignment="Left" Height="23" Margin="98,59,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="textLocalPort" HorizontalAlignment="Left" Height="23" Margin="98,104,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<TextBox x:Name="textFriendsIp" HorizontalAlignment="Left" Height="23" Margin="342,59,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" TextChanged="textBox2_TextChanged"/>
<TextBox x:Name="textFriendsPort" HorizontalAlignment="Left" Height="23" Margin="342,104,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<Button x:Name="button" Content="Start" HorizontalAlignment="Left" Margin="488,58,0,0" VerticalAlignment="Top" Width="96" Click="button_Click"/>
<ListBox x:Name="listMessage" HorizontalAlignment="Left" Height="156" Margin="39,151,0,0" VerticalAlignment="Top" Width="423"/>
<TextBox x:Name="textMessage" HorizontalAlignment="Left" Height="39" Margin="39,343,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="423"/>
<Button x:Name="button1" Content="Send" HorizontalAlignment="Left" Margin="488,362,0,0" VerticalAlignment="Top" Width="96" Click="button1_Click"/>
<Label x:Name="label4" Content="C1" HorizontalAlignment="Left" Margin="98,28,0,0" VerticalAlignment="Top" RenderTransformOrigin="-0.585,0.964"/>
<Label x:Name="label5" Content="C2" HorizontalAlignment="Left" Margin="342,28,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.105,1.107"/>
</Grid>
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 Chat_Client
{
public partial class MainWindow : Window
{
Socket sck;
EndPoint epLocal, epRemote;
public MainWindow()
{
InitializeComponent();
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
textLocalIp.Text = GetLocalIP();
textFriendsIp.Text = GetLocalIP();
}
private string GetLocalIP()
{
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach(IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
return "127.0.0.1";
}
private void MessageCallBack(IAsyncResult aResult)
{
try
{
int size = sck.EndReceiveFrom(aResult, ref epRemote);
if (size > 0)
{
byte[] recievedData = new byte[1464];
recievedData = (byte[])aResult.AsyncState;
ASCIIEncoding eEncoding = new ASCIIEncoding();
string recievedMessage = eEncoding.GetString(recievedData);
listMessage.Items.Add("Merid: " + recievedMessage);
}
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}
catch(Exception exp)
{
MessageBox.Show(exp.ToString());
}
}
private void textBox2_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void button_Click(object sender, RoutedEventArgs e)
{
try
{
epLocal = new IPEndPoint(IPAddress.Parse(textLocalIp.Text), Convert.ToInt32(textLocalPort.Text));
sck.Bind(epLocal);
epRemote = new IPEndPoint(IPAddress.Parse(textFriendsIp.Text), Convert.ToInt32(textFriendsPort.Text));
sck.Connect(epRemote);
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
button.Content = "Connected";
button.IsEnabled = false;
button1.IsEnabled = true;
textMessage.Focus();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
try
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] msg = new byte[1500];
msg = enc.GetBytes(textMessage.Text);
sck.Send(msg);
listMessage.Items.Add("Bod: "+textMessage);
textMessage.Clear();
}
catch(Exception excp)
{
MessageBox.Show(excp.ToString());
}
}
}
}

You are trying to access a GUI item from a background thread.
You can use the Dispatcher to do it on the main thread:
Dispatcher.Invoke(new Action(() => listMessage.Items.Add("Merid: " + recievedMessage)));
Anyway, the recommended way in WPF to interact with the GUI is DataBinding and separation of concerns with MVVM pattern.

Related

Richtextbox with color and save,load the richtextbox with color into a rtf file in wpf c#

How can i make a richtextbox that supports color and saves the richtextbox content in a rtf file with wpf and c#? I want that the user can select a word in a richtextbox and give it a special font color. And that the user can save the richtextbox with the special color into a .rtf file and load it back into the richtextbox with the special color.
Here you have something to get you started:
Write a filename with path like "C:\test.rtf"
Click on "Open" even if the file is new.
Add some text below "Document"
Select a word and click on the ".. add color.. " button.
Save the file.
Restart the program and open the file. The text should appear in the Document field.
XAML:
<Window x:Class="WpfApp11.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:WpfApp11"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="File path: "/>
<TextBox x:Name="filePathBox" Width="300" Margin="5,0,0,0"/>
</StackPanel>
<Button x:Name="open" Click="open_Click" Content="Open" Width="300" Margin="0,5,0,0" HorizontalAlignment="Left"/>
<TextBlock Text="Document" Margin="0,5,0,0"/>
<RichTextBox x:Name="richTextBox" Margin="0,5,0,0"/>
<Button x:Name="addColor" Click="addColor_Click" Content="Select and press this button to add color to text" Width="300" Margin="0,5,0,0" HorizontalAlignment="Left"/>
<Button x:Name="save" Click="save_Click" Content="Save" Width="300" Margin="0,5,0,0" HorizontalAlignment="Left"/>
<TextBlock Text="Status"/>
<TextBlock x:Name="statusBox" Width="300" Margin="0,5,0,0" HorizontalAlignment="Left"/>
</StackPanel>
</Grid>
</Window>
Code behind (xaml.cs)
using System;
using System.IO;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
namespace WpfApp11
{
public partial class MainWindow : Window
{
public MainWindow()
{
DataContext = this;
InitializeComponent();
}
private void addColor_Click(object sender, RoutedEventArgs e)
{
richTextBox.Selection.ApplyPropertyValue(ForegroundProperty, new SolidColorBrush(Colors.Red));
}
private void open_Click(object sender, RoutedEventArgs e)
{
try
{
TextRange range;
FileStream fStream;
string filename = filePathBox.Text;
if (File.Exists(filename))
{
range = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
using (fStream = new FileStream(filename, FileMode.OpenOrCreate))
{
range.Load(fStream, DataFormats.Rtf);
fStream.Close();
}
statusBox.Text = "File opened.";
}
else
{
statusBox.Text = "File new.";
}
}
catch (Exception excep)
{
statusBox.Text = excep.Message;
}
}
private void save_Click(object sender, RoutedEventArgs e)
{
try
{
TextRange range;
FileStream fStream;
range = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
string filename = filePathBox.Text;
using (fStream = new FileStream(filename, FileMode.Create))
{
range.Save(fStream, DataFormats.Rtf);
fStream.Close();
}
statusBox.Text = "File saved.";
}
catch (Exception excep)
{
statusBox.Text = excep.Message;
}
}
}
}

Why is my textbox loaded text disappearing

I have a textbox ACLBox that I want to display a string upon initialization of the user interface. Upon initializing, the string flashes for a second then disappears. Why?
Here's the xaml code for the textbox:
<Window x:Class="Funnel.ACL"
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:Funnel"
mc:Ignorable="d"
Title="ACL Configuration" Height="300" Width="560" WindowStartupLocation="CenterScreen"
Closing="exitACL"
Background="LightGray" Name="ACLConfiguration">
<Grid>
<DockPanel>
<Grid x:Name="FunnelGrid" DockPanel.Dock="Top" ShowGridLines="False">
<!--Defining Grid-->
<Grid.ColumnDefinitions>
<ColumnDefinition Width="130"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="30"/>
<ColumnDefinition Width="70"/>
<ColumnDefinition Width="75"/>
<ColumnDefinition Width="75"/>
<ColumnDefinition Width="75"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label x:Name="Config"
Content="ACL CONFIGURATION"
Grid.Row="0"
Grid.Column="0"
Grid.ColumnSpan="9"
HorizontalAlignment="Center"
Foreground="Blue"
FontWeight="Heavy"
FontSize="16">
</Label>
<CheckBox x:Name="aclCheckbox"
FlowDirection="RightToLeft"
Content="ACL ON"
Foreground="Blue"
FontWeight="Heavy"
FontSize="16"
Grid.Row="1"
Grid.Column="0"
Grid.RowSpan="1"
Grid.ColumnSpan="5"
HorizontalAlignment="Center"
Checked="ACL_Check"
Unchecked="ACL_Unchecked"
/>
<Label x:Name="AddIPAddress" Content="Add IP Address" Grid.Row="2" Grid.Column="0" Width="90" Height="30"></Label>
<TextBox x:Name="AddIPTextBox1" Grid.Row="2" Grid.Column="1" Width="35" Height="20" TextChanged="AddIPTextBox1_TextChanged"></TextBox>
<TextBox x:Name="AddIPTextBox2" Grid.Row="2" Grid.Column="2" Width="35" Height="20" TextChanged="AddIPTextBox2_TextChanged"></TextBox>
<TextBox x:Name="AddIPTextBox3" Grid.Row="2" Grid.Column="3" Width="35" Height="20" TextChanged="AddIPTextBox3_TextChanged"></TextBox>
<TextBox x:Name="AddIPTextBox4" Grid.Row="2" Grid.Column="4" Width="35" Height="20" TextChanged="AddIPTextBox4_TextChanged"></TextBox>
<TextBox x:Name="AddErrorBox" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Right" BorderThickness="0" Background="LightGray" FontSize="10" Text="{Binding AddErrorText}"/>
<Button x:Name="AddButton" Grid.Row="3" Grid.Column="1" Grid.ColumnSpan="4" HorizontalAlignment="Center" Height="25" Width="50" Click="addClick" FontSize="12" FontWeight="ExtraBold" Background="LightSteelBlue" VerticalAlignment="Top">ADD</Button>
<Label x:Name="DelIPAddress" Content="Remove IP Address" Grid.Row="4" Grid.Column="0" Width="120" Height="30"></Label>
<TextBox x:Name="DeleteIPTextBox1" Grid.Row="4" Grid.Column="1" Width="35" Height="20" TextChanged="DeleteIPTextBox1_TextChanged"></TextBox>
<TextBox x:Name="DeleteIPTextBox2" Grid.Row="4" Grid.Column="2" Width="35" Height="20" TextChanged="DeleteIPTextBox2_TextChanged"></TextBox>
<TextBox x:Name="DeleteIPTextBox3" Grid.Row="4" Grid.Column="3" Width="35" Height="20" TextChanged="DeleteIPTextBox3_TextChanged"></TextBox>
<TextBox x:Name="DeleteIPTextBox4" Grid.Row="4" Grid.Column="4" Width="35" Height="20" TextChanged="DeleteIPTextBox4_TextChanged"></TextBox>
<TextBox x:Name="DelErrorBox" Grid.Row="5" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Right" BorderThickness="0" Background="LightGray" FontSize="10" Text="{Binding DelErrorText}"/>
<Button x:Name="DeleteButton" Grid.Row="5" Grid.Column="1" Grid.ColumnSpan="4" HorizontalAlignment="Center" Height="25" Width="50" Click="deleteClick" FontSize="12" FontWeight="ExtraBold" Background="LightSteelBlue" VerticalAlignment="Top">DELETE</Button>
<Button x:Name="DeleteAllButton" Grid.Row="6" Grid.Column="1" Grid.ColumnSpan="4" HorizontalAlignment="Center" Height="25" Width="80" Click="deleteAllClick" FontSize="12" FontWeight="ExtraBold" Background="LightSteelBlue" VerticalAlignment="Top">REMOVE ALL</Button>
<Label x:Name="ACLBoxLabel" Content="Access Control List" Foreground="Blue" Grid.Row="1" Grid.Column="6" Grid.ColumnSpan="3" HorizontalAlignment="Center"></Label>
<TextBox x:Name="ACLBox"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.CanContentScroll="True"
Grid.Row="2"
Grid.Column="6"
Grid.RowSpan="4"
Grid.ColumnSpan="4"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Width="220"
Height="150"
FontSize="14"
IsReadOnly="True"
Text="{Binding ACLBoxText}"
TextWrapping="Wrap"
TextAlignment="Center" />
</Grid>
</DockPanel>
</Grid>
Here's the C# code for the string:
using System;
using System.Collections.Generic;
using System.ComponentModel;
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.Shapes;
namespace Funnel
{
/// <summary>
/// Interaction logic for ACL.xaml
/// </summary>
public partial class ACL : Window
{
AclManager _manage = new AclManager();
FileController _controller = new FileController();
string addStr1;
string addStr2;
string addStr3;
string addStr4;
bool addError;
string delStr1;
string delStr2;
string delStr3;
string delStr4;
bool delError;
public string aclText;
public event PropertyChangedEventHandler PropertyChanged;
public ACL()
{
InitializeComponent();
if(FunnelGlobals.accessControlList)
{
aclCheckbox.IsChecked = true;
}
aclText = _manage.getAclList();
}
private void exitACL(object sender,System.ComponentModel.CancelEventArgs e)
{
_controller.writeAclFile();
}
private void ACL_Check(object sender, RoutedEventArgs e)
{
FunnelGlobals.accessControlList = true;
aclText = _manage.getAclList();
}
private void ACL_Unchecked(object sender, RoutedEventArgs e)
{
FunnelGlobals.accessControlList = false;
aclText = _manage.getAclList();
}
private void AddIPTextBox1_TextChanged(object sender, TextChangedEventArgs e)
{
AddErrorBox.Text = "";
AddIPTextBox1.Text = AddIPTextBox1.Text;
addStr1 = AddIPTextBox1.Text;
if(!_manage.isDigit(addStr1))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
AddErrorBox.Foreground = errBrush;
AddErrorBox.Text = "Character NOT Valid";
addError = true;
}
else
{
addError = false;
}
ACLBox.Text = _manage.getAclList();
}
private void AddIPTextBox2_TextChanged(object sender, TextChangedEventArgs e)
{
AddErrorBox.Text = "";
AddIPTextBox2.Text = AddIPTextBox2.Text;
addStr2 = AddIPTextBox2.Text;
if (!_manage.isDigit(addStr2))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
AddErrorBox.Foreground = errBrush;
AddErrorBox.Text = "Character NOT Valid";
}
aclText = _manage.getAclList();
}
private void AddIPTextBox3_TextChanged(object sender, TextChangedEventArgs e)
{
AddErrorBox.Text = "";
AddIPTextBox3.Text = AddIPTextBox3.Text;
addStr3 = AddIPTextBox3.Text;
if (!_manage.isDigit(addStr3))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
AddErrorBox.Foreground = errBrush;
AddErrorBox.Text = "Character NOT Valid";
}
aclText = _manage.getAclList();
}
private void AddIPTextBox4_TextChanged(object sender, TextChangedEventArgs e)
{
AddErrorBox.Text = "";
AddIPTextBox4.Text = AddIPTextBox4.Text;
addStr4 = AddIPTextBox4.Text;
if (!_manage.isDigit(addStr4))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
AddErrorBox.Foreground = errBrush;
AddErrorBox.Text = "Character NOT Valid";
}
aclText = _manage.getAclList();
}
private void addClick(object sender, RoutedEventArgs e)
{
String addStr = addStr1 + "." + addStr2 + "." + addStr3 + "." + addStr4;
if(_manage.isLegit(addStr))
{
FunnelGlobals.aclIPs.Add(addStr);
}
if(addError)
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
AddErrorBox.Foreground = errBrush;
AddErrorBox.Text = "Fix Invalid Characters before Adding";
}
else
{
aclText = _manage.getAclList();
}
}
private void DeleteIPTextBox1_TextChanged(object sender, TextChangedEventArgs e)
{
DelErrorBox.Text = "";
DeleteIPTextBox1.Text = DeleteIPTextBox1.Text;
delStr1 = DeleteIPTextBox1.Text;
if (!_manage.isDigit(delStr1))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
DelErrorBox.Foreground = errBrush;
DelErrorBox.Text = "Character NOT Valid";
delError = true;
}
else
{
delError = false;
}
}
private void DeleteIPTextBox2_TextChanged(object sender, TextChangedEventArgs e)
{
DelErrorBox.Text = "";
DeleteIPTextBox2.Text = DeleteIPTextBox2.Text;
delStr2 = DeleteIPTextBox2.Text;
if (!_manage.isDigit(delStr2))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
DelErrorBox.Foreground = errBrush;
DelErrorBox.Text = "Character NOT Valid";
delError = true;
}
else
{
delError = false;
}
}
private void DeleteIPTextBox3_TextChanged(object sender, TextChangedEventArgs e)
{
DelErrorBox.Text = "";
DeleteIPTextBox3.Text = DeleteIPTextBox3.Text;
delStr3 = DeleteIPTextBox3.Text;
if (!_manage.isDigit(delStr3))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
DelErrorBox.Foreground = errBrush;
DelErrorBox.Text = "Character NOT Valid";
delError = true;
}
else
{
delError = false;
}
}
private void DeleteIPTextBox4_TextChanged(object sender, TextChangedEventArgs e)
{
DelErrorBox.Text = "";
DeleteIPTextBox4.Text = DeleteIPTextBox4.Text;
delStr4 = DeleteIPTextBox4.Text;
if (!_manage.isDigit(delStr4))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
DelErrorBox.Foreground = errBrush;
DelErrorBox.Text = "Character NOT Valid";
delError = true;
}
else
{
delError = false;
}
}
private void deleteClick(object sender, RoutedEventArgs e)
{
String delStr = delStr1 + "." + delStr2 + "." + delStr3 + "." + delStr4;
FunnelGlobals.aclIPs.Remove(delStr);
if (delError)
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
DelErrorBox.Foreground = errBrush;
DelErrorBox.Text = "Fix Invalid Characters before Removing";
}
else
{
aclText = _manage.getAclList();
}
}
private void deleteAllClick(object sender, RoutedEventArgs e)
{
FunnelGlobals.aclIPs.Clear();
aclText = _manage.getAclList();
}
private void ACLBox_Loaded(object sender, RoutedEventArgs e)
{
ACLBox.Text = _manage.getAclList();
}
public string ACLBoxText
{
get { return aclText; }
set { aclText = value; OnNotifyPropertyChanged("ACLBoxText"); }
}
private void OnNotifyPropertyChanged(string v)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(v));
throw new NotImplementedException();
}
}
}
Upon initializing, the string flashes for a second then disappears. Why?
Probably because you are "overwriting" the value of the ACLBoxText source property, which is initially displayed in the TextBlock, when you set the Text property of the TextBlock in your Loaded event handler.
If the TextBlock is empty once the UI has been loaded you should make sure that the _manage.getAclList() method returns the string that you expect it to return. You could temporarily try to assign the Text property to a "static" value:
private void ACLBox_Loaded(object sender, RoutedEventArgs e)
{
ACLBox.Text = "TEXT";
}
But I agree that it doesn't make much sense to first bind the Text property of the TextBlock to a source property in the XAML markup and then handle the Loaded event of the same TextBlock and set its Text property to a new value in this event handler. But I guess you have your reasons...
Note that binding that you define in the XAML markup will get reset when you programmatically set the Text property in your Loaded handler though.
So you should either don't bind the Text property in the XAML markup, or don't handle the Loaded event and set the Text property programmatically. It's one or the other but not both.
I figured out the problem. This is my first C# project and first time ever using Xaml (wpf) so I misunderstood binding. I bound the text like I did in the primary gui. The text is never getting triggered within this gui so I could only see the text flash because of loaded but then the text binding reset the textbox to nothing. When I changed my text to not be bound then everything works as I wanted. Lesson learned. Binding is only needed when accessing a textbox from within .cs files. It is not needed within xaml.cs. Since my text would only ever be triggered by xaml.cs just setting text the usual way(ie textbox.text = "whatever") does what I need. Thank you everyone for your help. I understand binding much, much better now. Java does things differently. :)
As Ed Plunkett has already mentioned, you should use your ACLBoxText backing variable instead of resetting the control value.
Something like this will work:
private void ACLBox_Loaded(object sender, RoutedEventArgs e)
{
ACLBoxText = _manage.getAclList();
}
Unfortunately, the view doesn't know about changes to backing properties unless you tell it that something changed. You need to implement INotifyPropertyChanged:
private string _aclBoxText;
public string ACLBoxText {
get { return _aclBoxText; }
set {
_aclBoxText = value;
OnNotifyPropertyChanged("ACLBoxText");
}
}
protected void OnNotifyPropertyChanged(string name)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));
}
public event PropertyChangedEventHandler PropertyChanged;

If combobox selected then show

I have to load a form and in this form I want to hide certain labels and text-boxes. In addition I want to show labels and text-boxes matching the conditionif combo-box selected =="Something"
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.Text == "Something")
{
label1.Show();
label2.Show();
textBox1.Show();
textBox2.Show();
}
}
How do I get these labels and text-boxes shown after I had selected a combo-box
try
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue == "Something")
{
label1.Visible = true;
label2.Visible = true;
textBox1.Visible = true;
textBox2.Visible = true;
}
}
I would try it like so, no need for an if:
label1.Visible = label2.Visible = textBox1.Visible = textBox2.Visible =
comboBox1.SelectedValue.toString() == "Something";
Try the following code
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var item = (ComboBoxItem)ComboBox.SelectedItem;
if (item == null)
return;
var content = (string) item.Content;
if(content == "Something")
{
label1.Visible = true;
label2.Visible = true;
textBox1.Visible = true;
textBox2.Visible = true;
}
}
It might be helpful to take a closer look at how the ComboBox and it's related properties function. The problem you're having is probably related to the fact that the ".Text" field doesn't reflect the currently selected item.
SelectedItem: Gets or sets currently selected item in the ComboBox.
Based on ComboBox.SelectionChangeCommitted
Text: Gets or sets the text associated with this control. (Overrides Control.Text.)
setting the text value will change the current value of the combobox
SelectedValue: Gets or sets the value of the member property specified by the ValueMember property. (Inherited from ListControl.)
Based on ListControl.SelectedValueChanged
Source msdn
Further reading at dotnetperls.
Build this demo program I made for learning to see it in action.
XAML
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="220" Width="711" Background="#FF6937D4">
<Grid>
<TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="23" Margin="10,38,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="333"/>
<ComboBox x:Name="comboBox1" SelectedValuePath="Content" HorizontalAlignment="Left" Margin="10,7,0,0" VerticalAlignment="Top" Width="120" SelectionChanged="comboSelectChanged">
<ComboBoxItem Content="Zero" Tag="Tag_Zero"/>
<ComboBoxItem Content="One" Tag="Tag_One"/>
<ComboBoxItem Content="Two" Tag="Tag_Two"/>
<ComboBoxItem Content="Three" Tag="Tag_Three"/>
</ComboBox>
<TextBox x:Name="textBox2" HorizontalAlignment="Left" Height="23" Margin="10,66,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="333"/>
<TextBox x:Name="textBox3" HorizontalAlignment="Left" Height="23" Margin="10,94,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="333"/>
<TextBox x:Name="textBox4" HorizontalAlignment="Left" Height="23" Margin="10,122,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="333"/>
<Label Content="comboBox1.SelectedItem.ToString()" HorizontalAlignment="Left" Margin="348,38,0,0" VerticalAlignment="Top" Foreground="White" Height="23" Width="215" Padding="7,3,0,0" ScrollViewer.CanContentScroll="True" UseLayoutRounding="True"/>
<Label Content="comboBox1.Text" HorizontalAlignment="Left" Margin="348,66,0,0" VerticalAlignment="Top" Foreground="White" Height="23" Width="215" Padding="7,3,0,0" ScrollViewer.CanContentScroll="True" UseLayoutRounding="True"/>
<Label Content="comboBox1.SelectedIndex.ToString()" HorizontalAlignment="Left" Margin="348,94,0,0" VerticalAlignment="Top" Foreground="White" Height="23" Width="215" Padding="7,3,0,0" ScrollViewer.CanContentScroll="True" UseLayoutRounding="True"/>
<Label Content="comboBox1.SelectedValue.ToString()" HorizontalAlignment="Left" Margin="348,122,0,0" VerticalAlignment="Top" Foreground="White" Height="23" Width="215" Padding="7,3,0,0" ScrollViewer.CanContentScroll="True" UseLayoutRounding="True"/>
<TextBox x:Name="textBox5" HorizontalAlignment="Left" Height="23" Margin="10,150,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="333"/>
<Label Content=" (comboBox1.SelectedItem as ComboBoxItem).Content as string" HorizontalAlignment="Left" Margin="348,150,-119,0" VerticalAlignment="Top" Foreground="White" Height="23" Width="360" Padding="7,3,0,0" ScrollViewer.CanContentScroll="True" UseLayoutRounding="True"/>
<Button x:Name="btnSelect" Content="Select based on value" HorizontalAlignment="Left" Margin="175,7,0,0" VerticalAlignment="Top" Width="168" Click="btnSelect_Click"/>
</Grid>
XAML.CS
using System;
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow() {
InitializeComponent();
}
private void comboSelectChanged(object sender, SelectionChangedEventArgs e) {
textBox1.Text = comboBox1.SelectedItem.ToString();
textBox2.Text = comboBox1.Text;
textBox3.Text = comboBox1.SelectedIndex.ToString();
textBox4.Text = comboBox1.SelectedValue.ToString();
textBox5.Text = (comboBox1.SelectedItem as ComboBoxItem).Content as string;
}
private void btnSelect_Click(object sender, RoutedEventArgs e) {
// Winform working code: comboBox1.SelectedIndex = comboBox1.FindString("string");
// WPF - This REQUIRES "SelectedValuePath="Content"" in XAML combobox def.
comboBox1.SelectedValue = "Three";
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue == "Something")
{
label1.Visible = true;
label2.Visible = true;
textBox1.Visible = true;
textBox2.Visible = true;
}
}
set autoPostback true for dropdown.
private void cmbPosition_SelectedIndexChanged(object sender, EventArgs e)
{
if(cmbPosition.Text =="Staff")
{
label11.Visible = true;
txtRole.Visible = true;
}
}
Try this:
private void datagrid_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
if (datagrid.SelectedItem == null || datagrid.SelectedItem.ToString() == "{NewItemPlaceholder}")
{
btnRemove.Visibility = System.Windows.Visibility.Hidden;
}
else
{
btnRemove.Visibility = System.Windows.Visibility.Visible;
}
}

ContactResultsData.DataContext not found

i want to get all my phone contacts in a list so i'm using those libraries and the *ID_CAP_CONTACTS* is checked in the WMAppManifest.xaml
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using System.Windows.Input;
using Microsoft.Phone.Shell;
using Microsoft.Phone.UserData;
but in my code the ContactResultsData.DataContext is not found
public MainPage()
{
InitializeComponent();
Contacts objContacts = new Contacts();
objContacts.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(objContacts_SearchCompleted);
objContacts.SearchAsync(string.Empty, FilterKind.None, null);
}
void objContacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
List<CustomContact> listOfContacts = new List<CustomContact>();
foreach (var result in e.Results)
{
CustomContact contact = new CustomContact();
contact.DisplayName = result.DisplayName;
var number = result.PhoneNumbers.FirstOrDefault();
if (number != null)
contact.Number = number.PhoneNumber;
else
contact.Number = "";
listOfContacts.Add(contact);
}
ContactResultsData.DataContext = listOfContacts;
}
}
private void ContactResultsData_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Contact contact = ContactResultsData.SelectedItem as Contact;
if (contact != null)
{
CustomContact customContact = new CustomContact(contact);
}
}
what is the problem what it needs please
i forget to add the ListBox ContactResultsData
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<StackPanel Height="Auto" Width="Auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,0,0,10" >
<TextBlock Name="ContactResultsLabel" Text="results are loading..." Style="{StaticResource PhoneTextLargeStyle}" TextWrapping="Wrap" />
<ListBox Name="ContactResultsData" ItemsSource="{Binding}" Height="436" Margin="12,0" SelectionMode="Multiple" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Name="ContactResults" FontSize="{StaticResource PhoneFontSizeMedium}" Text="{Binding Path=DisplayName, Mode=OneWay}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>

Start and stop MediaElement at specific times

I am change an app over to WPF, it plays audio and video and pictures all based on timed events .. I used "string MciCommand = string.Format("play frames FROM {0} to {1} {2}"" , before.
I have been searching and trying to fix this problem now in WPF c#
I have a video (wmv) and I have multiple sections that need to be played together.
example .. section1 start(200ms) stop(250ms) section2 start(5000ms) stop(15000ms)
finally I need it to pause on a a still frame ..
I have tried using a timer, and a empty while loop and it doesn't seek properly.
I am at a loss media element doesn't seem to support this type of use. I thought about wpfmediakit and direct show is very hard to wrap my novice wpf skills around.
any help would be greatly appreciated...
this was how I ended up solving my problem .. I used a list of properties and used it like a script that I loop through . and if the position in larger than the end time. it trigger the timer and goes to the next item in the list .. there is still some things that could be made a bit more refined .. like the textbox4 changed event also triggers next_item but it gets the job done .. for now ..
Hopefully this helps someone with the same issue ...
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.Windows.Media.Animation;
using System.ComponentModel;
using System.Threading;
namespace WpfApplication6
{
public partial class MainWindow : Window
{
BackgroundWorker position = new BackgroundWorker();
BackgroundWorker test_position = new BackgroundWorker();
public List<video_script> script_list = new List<video_script>();
int scrip_index;
public class video_script
{
public string action { get; set; }
public TimeSpan start_time { get; set; }
public TimeSpan endtime { get; set; }
public string filename { get; set; }
}
private void position_DoWork(object sender, DoWorkEventArgs e)
{
Thread.Sleep(100);
}
private void position_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (mediaElement1.Position > TimeSpan.FromMilliseconds(Convert.ToInt32(tb_endtime.Text)))
{
next_item();
}
else position.RunWorkerAsync();
textBox4.Text = "Play";
textBox3.Text = mediaElement1.Position.ToString();
}
public MainWindow()
{
InitializeComponent();
position.DoWork += new DoWorkEventHandler(position_DoWork);
position.RunWorkerCompleted += new RunWorkerCompletedEventHandler(position_RunWorkerCompleted);
position.WorkerSupportsCancellation = true;
test_position.DoWork += new DoWorkEventHandler(test_position_DoWork);
test_position.RunWorkerCompleted += new RunWorkerCompletedEventHandler(test_position_RunWorkerCompleted);
test_position.WorkerSupportsCancellation = true;
}
private void Mediasource_Click(object sender, RoutedEventArgs e)
{
if (!position.IsBusy) position.RunWorkerAsync();
mediaElement1.Source = new Uri(tb_filename.Text);
mediaElement1.LoadedBehavior = System.Windows.Controls.MediaState.Manual;
mediaElement1.UnloadedBehavior = System.Windows.Controls.MediaState.Manual;
mediaElement1.ScrubbingEnabled = true;
mediaElement1.Play();
}
private void stopbutton_Click(object sender, RoutedEventArgs e)
{
mediaElement1.Stop();
}
private void Playbutton_Click(object sender, RoutedEventArgs e)
{
scrip_index = 0;
mediaElement1.Play();
mediaElement1.LoadedBehavior = System.Windows.Controls.MediaState.Manual;
mediaElement1.UnloadedBehavior = System.Windows.Controls.MediaState.Manual;
mediaElement1.ScrubbingEnabled = true;
}
private void pausebutton_Click(object sender, RoutedEventArgs e)
{
if (mediaElement1.CanPause)
{
mediaElement1.Pause();
}
}
private void AddToListbutton_Click(object sender, RoutedEventArgs e)
{
video_script temp_item = new video_script();
temp_item.filename = tb_filename.Text;
temp_item.start_time = TimeSpan.FromMilliseconds(Convert.ToInt32(tb_starttime.Text));
temp_item.endtime = TimeSpan.FromMilliseconds(Convert.ToInt32(tb_endtime.Text));
temp_item.action = tb_action.Text;
script_list.Add(temp_item);
listBox1.Items.Add(temp_item.filename + " | " + tb_starttime.Text + " | " + tb_endtime.Text + " | " + tb_action.Text);
}
private void positionbox_TextChanged(object sender, TextChangedEventArgs e)
{
if (script_list.Count != 0)
{
if (script_list[scrip_index].endtime < mediaElement1.Position) next_item();
}
}
#region test button area
private void next_item()
{
if (scrip_index < script_list.Count() - 1)
{
scrip_index++;
switch (script_list[scrip_index].action)
{
case "Load":
mediaElement1.LoadedBehavior = System.Windows.Controls.MediaState.Manual;
mediaElement1.UnloadedBehavior = System.Windows.Controls.MediaState.Manual;
if (mediaElement1.Source != new Uri(script_list[scrip_index].filename)) mediaElement1.Source = new Uri(script_list[scrip_index].filename);
mediaElement1.ScrubbingEnabled = true;
playing = false;
next_item();
break;
case "Play":
mediaElement1.Play();
playing = true;
if(!test_position.IsBusy) test_position.RunWorkerAsync();
break;
case "Pause":
mediaElement1.Pause();
playing = false;
break;
case "Seek":
mediaElement1.Position = script_list[scrip_index].start_time;
playing = true;
break;
case "Stop":
mediaElement1.Stop();
playing = false;
break;
}
}
}
private void test_position_DoWork(object sender, DoWorkEventArgs e)
{
Thread.Sleep(100);
}
private void test_position_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (mediaElement1.Position > script_list[scrip_index].endtime )
{
next_item();
}
else test_position.RunWorkerAsync();
textBox4.Text = "Play";
textBox3.Text = mediaElement1.Position.ToString();
if (playing && !test_position.IsBusy) test_position.RunWorkerAsync();
}
private void testbutton_Click(object sender, RoutedEventArgs e)
{
if (mediaElement1.Source != new Uri(tb_filename.Text)) mediaElement1.Source = new Uri(tb_filename.Text);
mediaElement1.LoadedBehavior = System.Windows.Controls.MediaState.Manual;
mediaElement1.UnloadedBehavior = System.Windows.Controls.MediaState.Manual;
mediaElement1.Play();
mediaElement1.ScrubbingEnabled = true;
mediaElement1.Position = TimeSpan.FromMilliseconds(Convert.ToInt32(tb_starttime.Text));
if (test_position.IsBusy) test_position.CancelAsync();
if (!test_position.IsBusy) test_position.RunWorkerAsync();
}
bool playing;
#endregion
#region slider region
private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (slider1.Value > slider2.Value) slider2.Value = slider1.Value - 1;
}
private void slidermax_values_TextChanged(object sender, TextChangedEventArgs e)
{
slider1.Maximum = Convert.ToInt32(tb_slider_maxvalue.Text);
slider2.Maximum = Convert.ToInt32(tb_slider_maxvalue.Text);
}
private void slider2_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (slider2.Value < slider1.Value) slider1.Value = slider2.Value - 1;
}
#endregion
private void start_script_Click(object sender, RoutedEventArgs e)
{
scrip_index = -1;
next_item();
}
private void mediaElement1_MediaOpened(object sender, RoutedEventArgs e)
{
}
}
}
here is the Xaml for the form that I used for testing....
<Window x:Class="WpfApplication6.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="402" Width="922" WindowStyle="ThreeDBorderWindow">
<Grid>
<Button Content="mediasource load" Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="Mediasource_Click" />
<Button Content="play" Height="23" HorizontalAlignment="Left" Margin="10,43,0,0" Name="button2" VerticalAlignment="Top" Width="75" Click="Playbutton_Click" />
<Button Content="stop" Height="23" HorizontalAlignment="Left" Margin="10,142,0,0" Name="button5" VerticalAlignment="Top" Width="75" Click="stopbutton_Click" />
<Button Content="Pause" Height="23" HorizontalAlignment="Left" Margin="12,171,0,0" Name="button6" VerticalAlignment="Top" Width="75" Click="pausebutton_Click" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="165,296,0,0" Name="tb_starttime" VerticalAlignment="Top" Width="120" Text="{Binding ElementName=slider1, Path=Value, Mode=TwoWay}" />
<TextBox Height="23" HorizontalAlignment="Right" Margin="0,296,426,0" Name="tb_endtime" VerticalAlignment="Top" Width="120" Text="{Binding ElementName=slider2, Path=Value, Mode=TwoWay}" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="630,281,0,0" Name="textBox3" VerticalAlignment="Top" Width="120" TextChanged="positionbox_TextChanged" IsReadOnly="False" Text="{Binding ElementName=mediaElement1, Path=Position.Milliseconds, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="490,281,0,0" Name="textBox4" VerticalAlignment="Top" Width="134" />
<Label Content="filename" Height="28" HorizontalAlignment="Left" Margin="104,325,0,0" Name="label1" VerticalAlignment="Top" />
<ListBox Height="215" HorizontalAlignment="Left" Margin="469,10,0,0" Name="listBox1" VerticalAlignment="Top" Width="431" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="165,325,0,0" Name="tb_filename" VerticalAlignment="Top" Width="213" Text="C:\Data\001femod1\vid\dat1.avi" AcceptsTab="False" />
<Label Content="end time" Height="28" HorizontalAlignment="Left" Margin="291,294,0,0" Name="label2" VerticalAlignment="Top" />
<Label Content="start time" Height="28" HorizontalAlignment="Left" Margin="104,296,0,0" Name="label3" VerticalAlignment="Top" />
<Button Content="add to list" Height="23" HorizontalAlignment="Left" Margin="11,315,0,0" Name="button7" VerticalAlignment="Top" Width="75" Click="AddToListbutton_Click" />
<Label Content="Action" Height="28" HorizontalAlignment="Left" Margin="384,325,0,0" Name="label4" VerticalAlignment="Top" />
<ComboBox Height="23" HorizontalAlignment="Left" Margin="434,326,0,0" Name="tb_action" VerticalAlignment="Top" Width="120">
<ComboBoxItem Content="Play" />
<ComboBoxItem Content="Load" />
<ComboBoxItem Content="Stop" />
<ComboBoxItem Content="Pause" />
<ComboBoxItem Content="Seek" />
</ComboBox>
<Button Content="test times" Height="23" HorizontalAlignment="Left" Margin="50,246,0,0" Name="tb_test" VerticalAlignment="Top" Width="75" Click="testbutton_Click" />
<Slider Height="23" Margin="147,231,170,0" Name="slider1" VerticalAlignment="Top" SmallChange="1" LargeChange="10" IsSelectionRangeEnabled="False" IsMoveToPointEnabled="True" IsSnapToTickEnabled="True" ValueChanged="slider1_ValueChanged" />
<Slider Height="23" HorizontalAlignment="Left" Margin="147,260,0,0" Name="slider2" VerticalAlignment="Top" Width="583" SmallChange="1" IsSnapToTickEnabled="True" ValueChanged="slider2_ValueChanged" />
<Label Content="max value" Height="28" HorizontalAlignment="Left" Margin="736,226,0,0" Name="label5" VerticalAlignment="Top" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="736,247,0,0" Name="tb_slider_maxvalue" VerticalAlignment="Top" Width="120" Text="74000" TextChanged="slidermax_values_TextChanged" />
<Button Content="start script" Height="23" HorizontalAlignment="Left" Margin="10,281,0,0" Name="button3" VerticalAlignment="Top" Width="75" Click="start_script_Click" />
<MediaElement Height="215" HorizontalAlignment="Left" Margin="91,10,0,0" Name="mediaElement1" VerticalAlignment="Top" Width="372" MediaOpened="mediaElement1_MediaOpened" />
</Grid>
</Window>
Hmmm, that was tldnr for me so I'll offer up a route that worked for me for a UWP project that seems much simpler, but not sure if it'll work in your case:
For skipping to the right spots, use MediaPlayer.PlaybackSession.Position = TimeSpan.FromMilliseconds(yourDesiredPosition);
For knowing when to skip to the right spots (or do whatever else you need to, start, stop, switch source, whatever), just attach a position changed event:
Player.MediaPlayer.PlaybackSession.PositionChanged += PlaybackSession_PositionChanged;
private void PlaybackSession_PositionChanged(MediaPlaybackSession sender, object args)
{
var playa = sender.MediaPlayer;
if(playa.Position >= YourSpecialTimeSpan)
{
//do something, note can check state with sender.PlaybackState
}
}
hope this helps...

Categories