ContactResultsData.DataContext not found - c#

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>

Related

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;

C# WPF Getting error - System.InvalidOperationException:

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.

Dynamic Generation of Rows in WPF MVVM

I am creating a Data Entry Form having a ComboBox & Few TextBoxes in First Row. I want a new Row with same Elements to be Generated on Pressing Enter Key from Last TextBox in First Row.
How do i achieve it? Is there any Data Template or Item Template or anything as such that can work for this Data Entry Form.
I also read about Observable Collection Class & IEnumerable, can this help me achieving? How?
I am Newbie to WPF & MVVM, have done a lot of research but couldn't find the exact solution.
I have already done this,
<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="500" Width="420">
<Grid Name="_mainGrid" HorizontalAlignment="Left">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="227"/>
<ColumnDefinition Width="77" />
<ColumnDefinition Width="77" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="27"/>
</Grid.RowDefinitions>
</Grid>
</Window>
Also my .CS Code is as follows
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;
using System.Reflection;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
int rowIndex, Dr = 0, Cr = 0;
TextBox PTextBox, DrAmtTextBox, CrAmtTextBox;
ComboBox Combobox;
List<TextBox> txtboxParticulars = new List<TextBox>();
List<TextBox> txtboxDrAmount = new List<TextBox>();
List<TextBox> txtboxCrAmount = new List<TextBox>();
List<ComboBox> cmbboxDrCr = new List<ComboBox>();
public MainWindow()
{
InitializeComponent();
CreateRow();
}
public void CreateRow()
{
RowDefinition newRow = new RowDefinition();
newRow.Height = new GridLength(30, GridUnitType.Pixel);
_mainGrid.RowDefinitions.Insert(_mainGrid.RowDefinitions.Count - 1, newRow);
rowIndex = _mainGrid.RowDefinitions.Count - 2;
AddComboBox();
AddPTextBox();
AddDrCrTextBox();
}
public void AddComboBox()
{
Combobox = new ComboBox();
Combobox.Items.Add("Dr.");
Combobox.Items.Add("Cr.");
Combobox.SelectedItem = "Dr.";
Combobox.Height = 25;
Combobox.Name = "DrCr" + rowIndex.ToString();
Combobox.SelectionChanged += new SelectionChangedEventHandler(Combobox_SelectionChanged);
Combobox.KeyUp += new KeyEventHandler(Combobox_KeyUp);
Grid.SetRow(Combobox, rowIndex);
Grid.SetColumn(Combobox, 0);
_mainGrid.Children.Add(Combobox);
cmbboxDrCr.Add(new ComboBox { Text = Combobox.Name });
cmbboxDrCr[rowIndex].Text = "Dr.";
Combobox.Focus();
}
void Combobox_KeyUp(object sender, KeyEventArgs e)
{
if (Combobox.SelectedItem.ToString() == "Dr.")
{
cmbboxDrCr[rowIndex].Text = "Dr.";
DrAmtTextBox.Visibility = System.Windows.Visibility.Visible;
CrAmtTextBox.Visibility = System.Windows.Visibility.Hidden;
}
else
{
cmbboxDrCr[rowIndex].Text = "Cr.";
DrAmtTextBox.Visibility = System.Windows.Visibility.Hidden;
CrAmtTextBox.Visibility = System.Windows.Visibility.Visible;
}
}
void Combobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (Combobox.SelectedItem.ToString() == "Dr.")
{
cmbboxDrCr[rowIndex].Text = "Dr.";
DrAmtTextBox.Visibility = System.Windows.Visibility.Visible;
CrAmtTextBox.Visibility = System.Windows.Visibility.Hidden;
PTextBox.Focus();
}
else
{
cmbboxDrCr[rowIndex].Text = "Cr.";
DrAmtTextBox.Visibility = System.Windows.Visibility.Hidden;
CrAmtTextBox.Visibility = System.Windows.Visibility.Visible;
PTextBox.Focus();
}
}
public void AddPTextBox()
{
PTextBox = new TextBox();
PTextBox.Name = "Particulars" + rowIndex.ToString();
PTextBox.Height = 25;
PTextBox.Width = 225;
Grid.SetRow(PTextBox, rowIndex);
Grid.SetColumn(PTextBox, 1);
_mainGrid.Children.Add(PTextBox);
txtboxParticulars.Add(new TextBox { Text = PTextBox.Name });
}
public void AddDrCrTextBox()
{
DrAmtTextBox = new TextBox();
DrAmtTextBox.Name = "Dr" + rowIndex.ToString();
DrAmtTextBox.Height = 25;
DrAmtTextBox.Width = 75;
DrAmtTextBox.KeyDown += new KeyEventHandler(DrCrAmtTextBox_KeyDown);
Grid.SetRow(DrAmtTextBox, rowIndex);
Grid.SetColumn(DrAmtTextBox, 2);
_mainGrid.Children.Add(DrAmtTextBox);
txtboxDrAmount.Add(new TextBox { Text = DrAmtTextBox.Name });
CrAmtTextBox = new TextBox();
CrAmtTextBox.Name = "Cr" + rowIndex.ToString();
CrAmtTextBox.Height = 25;
CrAmtTextBox.Width = 75;
CrAmtTextBox.Visibility = System.Windows.Visibility.Hidden;
CrAmtTextBox.KeyDown += new KeyEventHandler(DrCrAmtTextBox_KeyDown);
Grid.SetRow(CrAmtTextBox, rowIndex);
Grid.SetColumn(CrAmtTextBox, 3);
_mainGrid.Children.Add(CrAmtTextBox);
txtboxCrAmount.Add(new TextBox { Text = DrAmtTextBox.Name });
}
void DrCrAmtTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
AddDataToList();
CountDrCr();
CreateRow();
}
}
void CountDrCr()
{
for (int i = 0; i <= rowIndex; i++)
{
if (cmbboxDrCr[i].Text == "Dr.")
{
Dr++;
}
else
{
Cr++;
}
}
}
void AddDataToList()
{
cmbboxDrCr[rowIndex].Text = Combobox.Text;
txtboxParticulars[rowIndex].Text = PTextBox.Text;
txtboxDrAmount[rowIndex].Text = CrAmtTextBox.Text;
txtboxCrAmount[rowIndex].Text = DrAmtTextBox.Text;
MessageBox.Show(cmbboxDrCr[rowIndex].Text +" "+ txtboxParticulars[rowIndex].Text + " " + txtboxDrAmount[rowIndex].Text + " " + txtboxCrAmount[rowIndex].Text);
}
}
}
I know this is not the Right way, so please help me with WPF MVVM method of doing this!!!
After going through the Answers here i have done the Following
Created a DataType
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DataTemplate
{
class YourDataType
{
public string DrCr { get; set; }
public string Particulars { get; set; }
public float Amount { get; set; }
public string Narration { get; set; }
}
}
MainWindow.Xaml File
<Window x:Class="DataTemplate.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DataTemplate"
Title="MainWindow" Height="350" Width="750">
<Grid>
<ListBox ItemsSource="{Binding YourCollection}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type local:YourDataType}">
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Horizontal">
<ComboBox SelectedIndex="0">
<ComboBoxItem Content="Dr."/>
<ComboBoxItem Content="Cr."/>
</ComboBox>
<TextBox Width="350"/>
<TextBox Width="150"/>
</StackPanel>
<Label Content="Narration"/>
<TextBox Width="450"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
MainWindow.CS File
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.Collections.ObjectModel;
namespace DataTemplate
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private ObservableCollection<YourDataType> YourCollection;
public MainWindow()
{
InitializeComponent();
YourCollection.Add(new YourDataType());
}
}
}
While it may seem natural for a non WPF developer to build their UI in code, that is generally not how it is done in WPF. Learn to do it in XAML and you will save yourself many headaches.
First create a data type, let's call it YourDataType for example, that contains all of the required properties for each 'row'. Then declare an ObservableCollection<YourDataType> property to data bind to a collection control, let's call it YourCollection. Finally, declare a DataTemplate that defines what each row should look like:
<ListBox ItemsSource="{Binding YourCollection}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type YourPrefix:YourDataType}">
<!-- Define your 'row' controls here -->
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Now to add a new empty row, all you need to do is to add a new item to your data bound collection:
YourCollection.Add(new YourDataType());
For further information, please refer to the Data Binding Overview page on MSDN.
You can create a WPF User Control with the complete structure inside (the comboBoxand and the textboxes), you can create a single list of this usercontrol
for example you can create a FormRow.xaml user control similar to this one....
<UserControl x:Class="WPFTEST.FormRow"
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"
mc:Ignorable="d"
Width="500" Height="26">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<ComboBox Margin="0"/>
<TextBox TextWrapping="Wrap" Text="TextBox" Grid.Column="1" Margin="0"/>
<TextBox TextWrapping="Wrap" Text="TextBox" Grid.Column="2" Margin="0"/>
<TextBox TextWrapping="Wrap" Text="TextBox" Grid.Column="3" Margin="0"/>
</Grid>
</UserControl>
And you can add events and control the model object information from the codebehind.....
in the main window you can have a listView or a Stack full of instances of this single control each instance is a view to a model object and preserves the acess hierarchy....

GART Augmented Reality issue

I'm working with windows phone 8 apps and want to add augmented reality feature and I'm using GART, but I experiencing the same issue
in there and even there is a solution by Igor Ralic by adding canvas.zindex to 1, I'm still experiencing the same issue (the items in world view flicker and disappear), so maybe there is anybody in here that having much better solution? I'm using mvvm patern to work with this AR
Here is my approach with mvvm
This is my mainviewmodel
private ObservableCollection<ARItem> _ardisplayLocation = null;
public ObservableCollection<ARItem> ardisplayLocation
{
get { return _ardisplayLocation; }
set { this.SetProperty(ref this._ardisplayLocation, value); }
}
private void UpdateTransport()
{
try
{
myMessage = "Loading web server data...";
WebClient client = new WebClient();
Uri uri = new Uri(transportURL1 + latitude + "%2C" + longitude + transportURL2, UriKind.Absolute);
client.DownloadStringCompleted += (s, e) =>
{
MainPage mainpage = new MainPage();
mainpage.RefreshButton();
if (e.Error == null)
{
RootObject result = JsonConvert.DeserializeObject<RootObject>(e.Result);
hereRestProperty = new ObservableCollection<Item>(result.results.items);
for (int i = 0; i < hereRestProperty.Count; i++)
{
ardisplayLocation.Add(new CityPlace()
{
GeoLocation = new GeoCoordinate(hereRestProperty[i].coordinate.Latitude,hereRestProperty[i].coordinate.Longitude),
Content = hereRestProperty[i].title,
Description = hereRestProperty[i].vicinity
});
}
}
else
{
isFailed = Visibility.Visible;
myMessage = "Failed to load web server data, please refresh";
}
isBusy = false;
};
client.DownloadStringAsync(uri);
}
catch (Exception)
{
isBusy = false;
isFailed = Visibility.Visible;
myMessage = "Something wrong happen, please refresh";
}
}
and here is my ArDisplay.xaml.cs
private MainViewModel mvm { get { return this.DataContext as MainViewModel; } }
public ArDisplay()
{
InitializeComponent();
DataContext = App.ViewModel;
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
ardisplay.StartServices();
ardisplay.ARItems = mvm.ardisplayLocation;
base.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
ardisplay.StopServices();
base.OnNavigatedFrom(e);
}
and my xaml
<gart:ARDisplay Name="ardisplay" AttitudeRefreshRate="50" MovementThreshold="10">
<gart:VideoPreview x:Name="videoPreview" Canvas.ZIndex="1"/>
<gart:WorldView x:Name="worldView" Canvas.ZIndex="1" ItemTemplate="{StaticResource CityItemTemplate}" MinItemScale="0.1" MaxItemScale="1.0" FarClippingPlane="300.0" NearClippingPlane="1.0"/>
<gart:HeadingIndicator x:Name="headingIndicator" Canvas.ZIndex="1" Width="300" Height="300" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</gart:ARDisplay>
and my data template
<DataTemplate x:Key="CityItemTemplate">
<Border BorderBrush="Black" BorderThickness="4" CornerRadius="8" Background="#FF003847" Width="320">
<StackPanel Margin="4">
<TextBlock x:Name="NameBlock" TextWrapping="NoWrap" Text="{Binding Content}" FontSize="38" VerticalAlignment="Center" Margin="0,0,4,0" Grid.Column="1" TextTrimming="WordEllipsis"/>
<TextBlock x:Name="DescriptionBlock" TextWrapping="Wrap" Text="{Binding Description}" FontSize="24" VerticalAlignment="Center" Margin="0,0,4,0" Grid.Column="1" TextTrimming="WordEllipsis" MaxHeight="168"/>
</StackPanel>
</Border>
</DataTemplate>
Canvas.ZIndex was missing from your DataTemplate
<DataTemplate x:Key="CityItemTemplate">
<Border BorderBrush="Black" BorderThickness="4" CornerRadius="8" Background="#FF003847" Width="320" Canvas.ZIndex="2">
<StackPanel Margin="4">
<TextBlock x:Name="NameBlock" TextWrapping="NoWrap" Text="{Binding Content}" FontSize="38" VerticalAlignment="Center" Margin="0,0,4,0" Grid.Column="1" TextTrimming="WordEllipsis"/>
<TextBlock x:Name="DescriptionBlock" TextWrapping="Wrap" Text="{Binding Description}" FontSize="24" VerticalAlignment="Center" Margin="0,0,4,0" Grid.Column="1" TextTrimming="WordEllipsis" MaxHeight="168"/>
</StackPanel>
</Border>
</DataTemplate>

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