Why is my textbox loaded text disappearing - c#

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;

Related

Timer button resetting

I am trying to make an auction application for my course.
namespace Auction
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
GetData("SELECT * FROM Produs");
btnLogout.Visibility = System.Windows.Visibility.Hidden;
btnAdd.Visibility = System.Windows.Visibility.Hidden;
btnBid.Visibility = System.Windows.Visibility.Hidden;
tb.Visibility = System.Windows.Visibility.Hidden;
}
private void GetData(string SelectCommand)
{
SqlConnection conn = new SqlConnection(#"Data Source=ISAAC;Initial Catalog=licitatie;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand(SelectCommand);
cmd.Connection = conn;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("prod");
sda.Fill(dt);
myGrid.DataContext = dt;
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
Login login = new Login();
login.Show();
Close();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Countdown(30, TimeSpan.FromSeconds(1), cur => tb.Text = cur.ToString());
}
void Countdown(int count, TimeSpan interval, Action<int> ts)
{
var dt = new System.Windows.Threading.DispatcherTimer();
dt.Interval = interval;
dt.Tick += (_, a) =>
{
if (count-- == 0)
{
MessageBox.Show("You have won this product!");
dt.Stop();
}
else
ts(count);
};
ts(count);
dt.Start();
}
private void btnLogout_Click(object sender, RoutedEventArgs e)
{
MainWindow main = new MainWindow();
main.Show();
Close();
MessageBox.Show("You are not logged. Please log in to bid", "Failed",
MessageBoxButton.OK, MessageBoxImage.Information);
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
Register reg = new Register();
reg.Show();
Close();
}
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var grid = sender as DataGrid;
var selected = grid.SelectedItem;
if (selected == grid.SelectedItem)
{
btnBid.Visibility = System.Windows.Visibility.Visible;
}
}
private void UpdateColumn()
{
}
}
}
This is main page you need to login. I read data from database. The problem is when I press bid button many times it is just resetting, but in background is working on. What do I need to do?
<Window x:Class="Auction.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="500" Width="800">
<Grid Margin="0,148,0,3" Name="myGrid" Background="#FF00286E">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="29*"/>
<ColumnDefinition Width="15*"/>
<ColumnDefinition Width="0*"/>
</Grid.ColumnDefinitions>
<Grid HorizontalAlignment="Left" Height="66" Margin="0,-68,0,0" VerticalAlignment="Top"
Width="792" Background="#FF00286E" Grid.ColumnSpan="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="12*"/>
<ColumnDefinition Width="13*"/>
</Grid.ColumnDefinitions>
<Button Content="Login" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Bottom"
Width="102" Height="35" Name="btnLogin" Click="btnLogin_Click">
<Button.Template>
<ControlTemplate TargetType="Button">
<TextBlock TextDecorations="Underline" Margin="0,0,0,-19" FontSize="24"
FontFamily="Verdana" FontWeight="Bold" FontStyle="Italic">
<ContentPresenter />
</TextBlock>
</ControlTemplate>
</Button.Template>
</Button>
<Button Content="Logout" Grid.Column="1" HorizontalAlignment="Left" Margin="300,10,0,0" VerticalAlignment="Bottom"
Width="102" Height="35" Name="btnLogout" Click="btnLogout_Click">
<Button.Template>
<ControlTemplate TargetType="Button">
<TextBlock TextDecorations="Underline" Margin="0,0,0,-19" FontSize="24"
FontFamily="Verdana" FontWeight="Bold" FontStyle="Italic">
<ContentPresenter />
</TextBlock>
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
<Grid HorizontalAlignment="Left" Height="78" Margin="0,-146,0,0" VerticalAlignment="Top" Width="792"
Grid.ColumnSpan="2" Background="#FF98BFD4">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="769*"/>
<ColumnDefinition Width="31*"/>
</Grid.ColumnDefinitions>
<Label Content="Welcome to Auction Application. Please Login to bid!" HorizontalAlignment="Center" Margin="44,28,0,0" VerticalAlignment="Top"
Height="40" Width="748" BorderThickness="3" FontSize="18" FontWeight="Bold" FontFamily="Verdana" Background="#FF98BFD4" Grid.ColumnSpan="2"/>
</Grid>
<Button Content="Bid" Grid.Column="1" HorizontalAlignment="Left" Margin="10,10,0,0"
VerticalAlignment="Top" Width="103" Height="29" FontSize="20" FontFamily="Verdana" FontStyle="Italic"
FontWeight="ExtraBold" Click="Button_Click" Name="btnBid"/>
<Button Content="Add User" Grid.Column="1" HorizontalAlignment="Left" Margin="10,255,0,0"
VerticalAlignment="Top" Width="103" Height="31" Name="btnAdd" Click="btnAdd_Click"/>
<DataGrid HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top"
Height="298" Width="502" Name="dataGrid1" ItemsSource="{Binding}"
SelectionChanged="DataGrid_SelectionChanged" AlternatingRowBackground="Coral">
</DataGrid>
<TextBox Grid.Column="1" HorizontalAlignment="Left" Height="48" Margin="10,119,0,0" TextWrapping="Wrap"
VerticalAlignment="Top" Width="144" Name="tb" FontSize="20" FontWeight="Bold" FontStyle="Italic" IsReadOnly="True"/>
</Grid>
</Window>
If I understand correctly, each time the user clicks the Bid button, you need to reset the timer. However, the previous timer continues. I haven't pasted your code into a project to test, but it appears to me that you need to make the dispatch timer a class field or property like this:
private DispatchTimer _dt = new System.Windows.Threading.DispatcherTimer();
Inside the event handler for Bid, stop the current _dt first followed by instantiating the new timer:
_dt.Stop();
_dt = new System.Windows.Threading.DispatcherTimer();
Try this change:
namespace Auction
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
//Class level field:
private DispatchTimer _dt = new System.Windows.Threading.DispatcherTimer();
public MainWindow()
{
InitializeComponent();
GetData("SELECT * FROM Produs");
btnLogout.Visibility = System.Windows.Visibility.Hidden;
btnAdd.Visibility = System.Windows.Visibility.Hidden;
btnBid.Visibility = System.Windows.Visibility.Hidden;
tb.Visibility = System.Windows.Visibility.Hidden;
}
private void GetData(string SelectCommand)
{
SqlConnection conn = new SqlConnection(#"Data Source=ISAAC;Initial Catalog=licitatie;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand(SelectCommand);
cmd.Connection = conn;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("prod");
sda.Fill(dt);
myGrid.DataContext = dt;
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
Login login = new Login();
login.Show();
Close();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Countdown(30, TimeSpan.FromSeconds(1), cur => tb.Text = cur.ToString());
}
void Countdown(int count, TimeSpan interval, Action<int> ts)
{
this._dt.Stop();
this._dt = new System.Windows.Threading.DispatcherTimer();
this._dt.Interval = interval;
this._dt.Tick += (_, a) =>
{
if (count-- == 0)
{
MessageBox.Show("You have won this product!");
this._dt.Stop();
}
else
ts(count);
};
ts(count);
this._dt.Start();
}
private void btnLogout_Click(object sender, RoutedEventArgs e)
{
MainWindow main = new MainWindow();
main.Show();
Close();
MessageBox.Show("You are not logged. Please log in to bid", "Failed",
MessageBoxButton.OK, MessageBoxImage.Information);
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
Register reg = new Register();
reg.Show();
Close();
}
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var grid = sender as DataGrid;
var selected = grid.SelectedItem;
if (selected == grid.SelectedItem)
{
btnBid.Visibility = System.Windows.Visibility.Visible;
}
}
private void UpdateColumn()
{
}
}
}

Can you access the gradient colour created in XAML in c# wpf

Similar questions may exists, but none of them seems to be helpful. So I'll try to explain a more specific case, and see if anyone can help me.
I have an application that has a label with a gradient background. I created the gradient background using XAML, my program changes the background fine, but I want the background to change back to "normal" after the user clicks the reset button. How can I do this as still new to wpf? The code in XAML "LinearGradientBrush x:Key="headerBackground" is what I want to access in code behind
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:syncfusion="http://schemas.syncfusion.com/wpf" x:Class="ItemWrapPanel.MainWindow"
Title="MainWindow" Height="350" Width="600">
<Window.Resources>
**<LinearGradientBrush x:Key="headerBackground" StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="#FFEFEEEE" Offset="0"/>
<GradientStop Color="#E7E7E7E7" Offset="1"/>
</LinearGradientBrush>**
<LinearGradientBrush x:Key="selectedHeaderBackground" StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="#F6CD1D" Offset="0"/>
<GradientStop Color="#EBA32A" Offset="1"/>
</LinearGradientBrush>
</Window.Resources>
<Grid x:Name="MainGrid">
<Grid.RowDefinitions>
<RowDefinition x:Name="Row1"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="Col1"/>
<ColumnDefinition x:Name="Col2"/>
<ColumnDefinition x:Name="Col3"/>
</Grid.ColumnDefinitions>
<Label x:Name="Label1"
Content="Rock Properties"
Grid.Row="0"
Grid.Column="0"
MouseDoubleClick="Label1_MouseDoubleClick"
Background="{DynamicResource headerBackground}"
VerticalAlignment="Top"/>
<Label x:Name="Label2"
Content="Contacts"
Grid.Column="1"
Grid.Row="0"
Background="{DynamicResource headerBackground}"
MouseDoubleClick="Label2_MouseDoubleClick"
Margin="0,0,0,282"
VerticalAlignment="Top"/>
<Label x:Name="Label3"
Content="Fluid Properties"
Grid.Column="2"
Background="{DynamicResource headerBackground}"
Grid.Row="0"
MouseDoubleClick="Label3_MouseDoubleClick"
Margin="0,0,0,282"
VerticalAlignment="Top"/>
<Button x:Name="Resetbtn" Content="Reset" HorizontalAlignment="Left" Margin="0,70,0,0" VerticalAlignment="Top" Width="75" Click="Reset_Click" Background="{DynamicResource selectedHeaderBackground}"/>
<Button Name="CloseRock" Content="X" HorizontalAlignment="Left" Margin="173,4,0,0" VerticalAlignment="Top" Width="24" Grid.Column="0"/>
<Button Name="CloseContacts" Content="X" HorizontalAlignment="Left" Margin="174,2,0,0" VerticalAlignment="Top" Width="24" Grid.Column="1"/>
<Button Name="CloseFluid" Content="X" HorizontalAlignment="Left" Margin="173,2,0,0" VerticalAlignment="Top" Width="24" Grid.Column="2"/>
</Grid>
C#
private ColumnDefinition SelectedColumn;
private Color selectedHeaderBackground = (Color)ColorConverter.ConvertFromString("#EBA32A");
public MainWindow()
{
InitializeComponent();
}
private void Label1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
SelectedColumn = Col1;
SetCol1Header();
SetColumnWidth();
SetColumnWidthCol1();
}
private void Label2_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
SelectedColumn = Col2;
SetCol2Header();
SetColumnWidth();
SetColumnWidthCol2();
}
private void Label3_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
SelectedColumn = Col3;
SetCol3Header();
SetColumnWidth();
SetColumnWidthCol3();
}
public void SetColumnWidth()
{
SelectedColumn.Width = new GridLength(1, GridUnitType.Star);
}
private void Reset_Click(object sender, RoutedEventArgs e)
{
ResetHeaderBackground();
ResetColumnWidth();
ResetColumns();
}
private void ResetColumns()
{
Label1.Visibility = System.Windows.Visibility.Visible;
}
private void ResetColumnWidth()
{
Col1.Width = new GridLength(1, GridUnitType.Star);
Col2.Width = new GridLength(1, GridUnitType.Star);
Col3.Width = new GridLength(1, GridUnitType.Star);
}
private void ResetHeaderBackground()
{
//Label3.Background = new SolidColorBrush(HeaderBackground);
//Label2.Background = new SolidColorBrush(HeaderBackground);
//Label1.Background = new SolidColorBrush(HeaderBackground);
}
private void MinimiseRock_Click(object sender, RoutedEventArgs e)
{
MinimiseWindow();
}
private void MinimiseContacts_Click(object sender, RoutedEventArgs e)
{
MinimiseWindow();
}
private void MinimiseFluid_Click(object sender, RoutedEventArgs e)
{
MinimiseWindow();
}
private void MinimiseWindow()
{
this.WindowState = WindowState.Minimized;
}
private void SetCol1Header()
{
Label1.Background = new SolidColorBrush(selectedHeaderBackground);
}
private void SetCol2Header()
{
Label2.Background = new SolidColorBrush(selectedHeaderBackground);
}
private void SetCol3Header()
{
Label3.Background = new SolidColorBrush(selectedHeaderBackground);
}
private void SetColumnWidthCol1()
{
Col2.Width = new GridLength(150);
Col3.Width = new GridLength(150);
}
private void SetColumnWidthCol2()
{
Col1.Width = new GridLength(150);
Col3.Width = new GridLength(150);
}
private void SetColumnWidthCol3()
{
Col1.Width = new GridLength(150);
Col2.Width = new GridLength(150);
}
}
You can access the Resources of your Window by invoking FindResource providing the key you have set for your Brush (and eventually cast it to LinearGradientBrush).
this.Label1.Background = (LinearGradientBrush)this.FindResource("headerBackground")
cheeers.

Infinity scroll bug with data template

After user get the end of longlistselector ItemRealized event fires items add successfully. But the button's tag is empty (for added items), for items that I got first time button's tag isn't null.
This is my xaml DataTemplate:
<DataTemplate x:Key="TitleSongDataTemplate" x:Name="Titledata">
<Border Background="{StaticResource PhoneForegroundBrush}" Margin="0,0,12,12">
<Grid x:Name="GridOfButtons" Background="{StaticResource PhoneForegroundBrush}" >
<Grid Margin="0, -6, -7, 0"
HorizontalAlignment="Right"
VerticalAlignment="Top" Height="81" Width="83">
<Button
Content=""
FontFamily="Segoe UI Symbol"
Style="{StaticResource RoundButton}"
x:Name="AddToMySongsButton"
Tag="{Binding Song}"
Background="{StaticResource PhoneBackgroundBrush}"
Click="AddToMySongsButton_Click"/>
</Grid>
<Grid
VerticalAlignment="Top"
HorizontalAlignment="Left"
Margin="-17,-6,0,0" Height="81" Width="95">
<Button FontFamily="Segoe UI Symbol"
Content=""
Style="{StaticResource RoundButton}" Margin="10,0,0,0"
x:Name="PlayButton"
Background="{StaticResource PhoneBackgroundBrush}"
Tag="{Binding Song}"
Click="PlayButton_Click"/>
</Grid>
<Grid
HorizontalAlignment="Center"
VerticalAlignment="Top"
Margin="69,-7,60,0" Height="82" Width="84">
<Button Style="{StaticResource RoundButton}"
Content=""
FontFamily="Segoe UI Symbol"
x:Name="DownloadButton"
Margin="-5,0,0,0"
Background="{StaticResource PhoneBackgroundBrush}"
Tag="{Binding Song}"
Click="DownloadButton_Click"/>
</Grid>
<StackPanel VerticalAlignment="Bottom">
<TextBlock Text="{Binding Title}" Foreground="{StaticResource PhoneBackgroundBrush}" Margin="6 , 4, 6, 4"/>
<TextBlock Text="{Binding Artist}" Foreground="Gray" Opacity="0.75" Margin="6, 0, 0, 6"/>
</StackPanel>
</Grid>
</Border>
</DataTemplate>
My pivot:
<phone:Pivot x:Name="MainTitle">
<phone:PivotItem Header="Rock">
<Grid>
<phone:LongListSelector x:Name="RockLongList"
GridCellSize="220,150"
LayoutMode="Grid"
ItemTemplate="{StaticResource TitleSongDataTemplate}"
ItemRealized="RockLongList_ItemRealized"/>
<TextBlock x:Name="RockText"
Text="Загрузка..."
FontSize="60"
Opacity="0.5"
Style="{StaticResource LongListSelectorGroupHeaderLetterTileStyle}"
Margin="0,10,10,10"
TextWrapping="Wrap"
HorizontalAlignment="Right"
Width="436"/>
</Grid>
</phone:PivotItem>
Here my infinity scrooling realization:
1.I fired ItemRealized
private void RockLongList_ItemRealized(object sender, ItemRealizationEventArgs e)
{
var nownum = offset + 50;
if (nownum >= usercount)
{
MainTitle.Title = "All songs've downloaded";
}
else
{
SpecialSongs.SongJSON song = e.Container.Content as SpecialSongs.SongJSON;
if (song != null)
{
int myoffset = 2;
// Only if there is no data that is currently getting loaded would be initiate the loading again
if (!isCurrentlyLoading && defaultBindList.Count - defaultBindList.IndexOf(song) <= myoffset)
{
LoadDataFromSource();
}
}
}
}
And finally:
private void LoadDataFromSource()
{
this.Dispatcher.BeginInvoke(() =>
{
MainTitle.Title = "Downloading test...";
});
//progressBar.IsVisible = true;
isCurrentlyLoading = true;
string UsersUri = string.Format("https://api.vk.com/method/audio.get?&count=50&access_token={0}&user_id={1}&version=4.92&offset={2}", AccessToken, uID, offset);
//var query = string.Format(datasourceUrl, currentPage);
WebClient client = new WebClient();
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadStringAsync(new Uri(UsersUri));
}
private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//Here handle exception
using (var reader = new MemoryStream(Encoding.Unicode.GetBytes(e.Result)))
{
SpecialSongs songs = JsonConvert.DeserializeObject<SpecialSongs>(e.Result);
this.Dispatcher.BeginInvoke(() =>
{
foreach (var tracks in songs.songs)
{
rockBindList.Add(tracks);
MainTitle.Title = "Downloaded test...";
}
RockLongList.ItemsSource = rockBindList;
isCurrentlyLoading = false;
//progressBar.IsVisible = false;
});
}
offset += 50;
}
This code shows why i need button's tag property:
private void DownloadButton_Click(object sender, RoutedEventArgs e)
{
try
{
SpecialSongs.SongJSON songdgd = (SpecialSongs.SongJSON)(sender as Button).Tag;
this.Download.Message = songdgd.Artist + "\n" + songdgd.Title;
string StringToSave = "shared/transfers/" + songdgd.Artist + songdgd.Title;
var linktosave = StringToSave.Replace(" ", "");
transferRequest = new BackgroundTransferRequest(new Uri(songdgd.URI, UriKind.RelativeOrAbsolute)) { Method = "GET" };
var uri = new Uri(linktosave, UriKind.Relative);
songdgd.URI = linktosave.Replace("shared/transfers/", "");
var json = JsonConvert.SerializeObject(songdgd);
var name = linktosave.Replace("shared/transfers/", "");
transferRequest.Tag = "json" + json + "json" + "uri" + name + "uri";
transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
transferRequest.DownloadLocation = uri;
try
{
BackgroundTransferService.Add(transferRequest);
}
catch
{
MessageBox.Show("Эта песня уже загружается.");
}
}
catch { MessageBox.Show("Error while downloading"); }
}
Thanks.

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;
}
}

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