Infinity scroll bug with data template - c#

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.

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;

Delete Column from Grid and have other columns reposition c#

I have a wpf application and I want to be able to delete a column from a grid and then have the other columns repositioned themselves (i.e. if the users deletes the first column all other columns move one to the left, if the user deletes the second column all other columns after the second one moves to the left) by the event of clicking a button. Currently I am only able to hide the items in the column, it leaves a white space which I don't want.
private void SetColumnWidthCol1()
{
Col2.Width = new GridLength(150);
Col3.Width = new GridLength(150);
Col4.Width = new GridLength(150);
}
private void SetColumnWidthCol2()
{
Col1.Width = new GridLength(150);
Col3.Width = new GridLength(150);
Col4.Width = new GridLength(150);
}
private void SetColumnWidthCol3()
{
Col1.Width = new GridLength(150);
Col2.Width = new GridLength(150);
Col4.Width = new GridLength(150);
}
private void SetColumnWidthCol4()
{
Col1.Width = new GridLength(150);
Col2.Width = new GridLength(150);
Col3.Width = new GridLength(150);
Col5.Width = new GridLength(150);
Col6.Width = new GridLength(150);
}
private void SetColumnWidthCol5()
{
Col1.Width = new GridLength(150);
Col2.Width = new GridLength(150);
Col3.Width = new GridLength(150);
Col4.Width = new GridLength(150);
Col6.Width = new GridLength(150);
}
private void SetColumnWidthCol6()
{
Col1.Width = new GridLength(150);
Col2.Width = new GridLength(150);
Col3.Width = new GridLength(150);
Col4.Width = new GridLength(150);
Col5.Width = new GridLength(150);
}
private void CloseRock_Click(object sender, RoutedEventArgs e)
{
RockLabel.Visibility = System.Windows.Visibility.Hidden;
CloseRock.Visibility = System.Windows.Visibility.Hidden;
}
private void CloseContacts_Click(object sender, RoutedEventArgs e)
{
ContactsLabel.Visibility = System.Windows.Visibility.Hidden;
CloseContacts.Visibility = System.Windows.Visibility.Hidden;
}
private void CloseFluid_Click(object sender, RoutedEventArgs e)
{
FluidLabel.Visibility = System.Windows.Visibility.Hidden;
CloseFluid.Visibility = System.Windows.Visibility.Hidden;
}
private void CloseRegions_Click(object sender, RoutedEventArgs e)
{
RegionsLabel.Visibility = System.Windows.Visibility.Hidden;
CloseRegions.Visibility = System.Windows.Visibility.Hidden;
}
private void CloseProbabilities_Click(object sender, RoutedEventArgs e)
{
ProbabilitiesLabel.Visibility = System.Windows.Visibility.Hidden;
CloseProbabilities.Visibility = System.Windows.Visibility.Hidden;
}
private void CloseEconomics_Click(object sender, RoutedEventArgs e)
{
EconomicsLabel.Visibility = System.Windows.Visibility.Hidden;
CloseEconomics.Visibility = System.Windows.Visibility.Hidden;
}
}
XAML
<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="1000">
<Window.Resources>
<LinearGradientBrush x:Key="LabelBackground" 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/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="Col1"/>
<ColumnDefinition x:Name="Col2"/>
<ColumnDefinition x:Name="Col3"/>
<ColumnDefinition x:Name="Col4"/>
<ColumnDefinition x:Name="Col5"/>
<ColumnDefinition x:Name="Col6"/>
</Grid.ColumnDefinitions>
<Label x:Name="RockLabel"
Background="{StaticResource LabelBackground}"
Content="Rock Properties"
Grid.Row="0"
Grid.Column="0"
MouseUp="RockLabel_MouseDoubleClick"
VerticalAlignment="Top"/>
<Label x:Name="ContactsLabel"
Content="Contacts"
Background="{StaticResource LabelBackground}"
Grid.Column="1"
Grid.Row="0"
MouseUp="ContactsLabel_MouseDoubleClick"
VerticalAlignment="Top"/>
<Label x:Name="FluidLabel"
Content="Fluid Properties"
Background="{StaticResource LabelBackground}"
Grid.Column="2"
Grid.Row="0"
MouseUp="FluidLabel_MouseDoubleClick"
VerticalAlignment="Top"/>
<Label x:Name="RegionsLabel"
Content="Regions"
Background="{StaticResource LabelBackground}"
Grid.Column="3"
Grid.Row="0"
MouseUp="RegionsLabel_MouseDoubleClick"
VerticalAlignment="Top"/>
<Label x:Name="ProbabilitiesLabel"
Content="Probabilities"
Background="{StaticResource LabelBackground}"
Grid.Column="4"
Grid.Row="0"
MouseUp="ProbabiltitesLabel_MouseDoubleClick"
VerticalAlignment="Top"/>
<Label x:Name="EconomicsLabel"
Content="Economics"
Background="{StaticResource LabelBackground}"
Grid.Column="5"
Grid.Row="0"
MouseUp="EconomicsLabel_MouseDoubleClick"
VerticalAlignment="Top"/>
<Button x:Name="Resetbtn" Content="Restore" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Click="Reset_Click" Margin="0,59,0,0"/>
<Button Name="CloseRock" Content="X" HorizontalAlignment="Right" Margin="0,2,0,0" VerticalAlignment="Top" Width="24" Grid.Column="0" Grid.Row="0" Click="CloseRock_Click"/>
<Button Name="CloseContacts" Content="X" HorizontalAlignment="Right" Margin="0,2,2,0" VerticalAlignment="Top" Width="24" Grid.Column="1" Grid.Row="0" Click="CloseContacts_Click"/>
<Button Name="CloseFluid" Content="X" HorizontalAlignment="Right" Margin="0,2,2,0" VerticalAlignment="Top" Width="24" Grid.Column="2" Grid.Row="0" Click="CloseFluid_Click"/>
<Button Name="CloseRegions" Content="X" HorizontalAlignment="Right" Margin="0,2,1,0" VerticalAlignment="Top" Width="24" Grid.Column="3" Grid.Row="0" Click="CloseRegions_Click"/>
<Button Name="CloseProbabilities" Content="X" HorizontalAlignment="Right" Margin="0,2,1,0" VerticalAlignment="Top" Width="24" Grid.Column="4" Grid.Row="0" Click="CloseProbabilities_Click"/>
<Button Name="CloseEconomics" Content="X" HorizontalAlignment="Right" Margin="0,2,1,0" VerticalAlignment="Top" Width="24" Grid.Column="5" Grid.Row="0" Click="CloseEconomics_Click"/>
</Grid>
Instead of Visibility.Hidden make them Visibility.Collapsed.
Like -
private void CloseContacts_Click(object sender, RoutedEventArgs e)
{
ContactsLabel.Visibility = System.Windows.Visibility.Collapsed;
CloseContacts.Visibility = System.Windows.Visibility.Collapsed;
}

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

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