how to showing time elapsed in a media element in silverlight? - silverlight

how can i showing time elapsed of a video file who is playing in a MediaElement control in silverlight?

There is a Position property on the MediaElement. This video and source code should help you out http://www.silverlight.net/learn/quickstarts/audioandvideo/

Finally i resolve my problem with this way:
i use a Textblock control and bind text property to Position property of MediaElement control, then i use a IvalueConverter to show appropriate Time in TextBlock:
<TextBlock MinWidth="40" Text="{Binding ElementName=myMediaElement, Path=Position, Converter={StaticResource TimeConverterFormatter}}"/>
TimeConverterFormatter is a class for convert TimeSpan value to short time format. because position property in MediaElement show a Timespan value like to "0:00:00:00.0000000" and i want elapsed time value like to this: "00:00"
public class TimeConverterFormatter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value.ToString().Length == 16)
return value.ToString().Substring(3, 2) + ":" + value.ToString().Substring(6, 2);
return value.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}

I realise that this is an old question now, but in WPF you can just use a normal StringFormat to do what you want:
<TextBlock Text="{Binding Position, ElementName=myMediaElement,
StringFormat={}{0:hh}:{0:mm}, FallbackValue=00:00, Mode=OneWay}" />
I couldn't work out whether you wanted hours and minutes or minutes and seconds, so here is the latter:
<TextBlock Text="{Binding Position, ElementName=myMediaElement,
StringFormat={}{0:mm}:{0:ss}, FallbackValue=00:00, Mode=OneWay}" />
I can't guarantee that it will work in Silverlight though.

Not sure about Silverlight but this should work to show mm:ss.
lblLength.Content = String.Format("{0:mm}:{0:ss}", mediaElement.Position);

Related

xaml change resolution changes the view's size

I have a view that is fixed in height and width, and im currently using a 4k monitor. when i run my application on a 1080p monitor, its blew things up. i have some lines and paths that are set at a certain margin, and so is other controls.
i have tried binding to the screen width and height (see below), but it didn't kept the screen size fix when change to other resolution. i also set ResizeMode to NoResize
Height="{Binding Source={x:Static SystemParameters.PrimaryScreenHeight}, Converter={k1:RatioConverter}, ConverterParameter='0.7'}"
Width="{Binding Source={x:Static SystemParameters.PrimaryScreenWidth}, Converter={k1:RatioConverter}, ConverterParameter='0.7'}"
here is the converter i got from #berhauz
[ValueConversion(typeof(string), typeof(string))]
public class RatioConverter : MarkupExtension, IValueConverter
{
private static RatioConverter _instance;
public RatioConverter() { }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{ // do not let the culture default to local to prevent variable outcome re decimal syntax
double size = System.Convert.ToDouble(value) * System.Convert.ToDouble(parameter, CultureInfo.InvariantCulture);
return size.ToString("G0", CultureInfo.InvariantCulture);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{ // read only converter...
throw new NotImplementedException();
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return _instance ?? (_instance = new RatioConverter());
}
}
is there a way to fix the screen size on every resolution so the lines,paths,controls will not jump around?
i found the simple solution was to wrap everything in the viewbox and bind the height and width of the viewbox to the primary screen
Height="{Binding Source={x:Static SystemParameters.PrimaryScreenHeight}, Converter={k1:RatioConverter}, ConverterParameter='0.7'}"
Width="{Binding Source={x:Static SystemParameters.PrimaryScreenWidth}, Converter={k1:RatioConverter}, ConverterParameter='0.7'}"
no matter what resolution you have, the contents inside my viewbox stayed the same and does not change sizes

Flexing date format in XAML at runtime

Based on a setting in my application I need to be able to show different formats of showing a Date in XAML. For example it needs to be either in "yyyy/MM/dd" format or in "MM/dd/yyyy" format.
What are some ways that I can achieve this? Please note that the places in my application that I need to handle this are limited so even a "fix on the spot" type of solution would work in my case too.
Thanks for suggestions.
You can use a ValueConverter for this. Just replace YourApplicationSettings.YearFirst with wherever you're pulling the setting from.
public class DateTime2FlexibleDateString : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var dt = value as DateTime?
if (dt== null)
{
return null;
}
var dateTime = dt.Value;
if (YourApplicationSettings.YearFirst)
{
return dateTime.ToString("yyyy/MM/dd");
}
return dateTime.ToString("MM/dd/yyyy");
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
Then either in each xaml file that needs it, or in a App.xaml (or a resource dictionary added to App.xaml), add a static resource for your converter.
<UserControl.Resources>
<converters:DateTime2FlexibleDateString x:Key="DateTime2FlexibleDateString" />
</UserControl.Resources>
And then when you bind to the date, specify the converter.
<TextBlock Text="{Binding MyDateTimeVariable, Converter={StaticResource DateTime2FlexibleDateString}" />
It depends on the context of what you are doing, but if you are binding to a DateTime then you can alter the StringFormat property like so:
<TextBlock Text="{Binding MyDateTimeVariable, StringFormat='yyyy/MM/dd'}" />
<TextBlock Text="{Binding MyDateTimeVariable, StringFormat='MM/dd/yyyy'}" />
Here is a good example of some different format options that be achieved like this.

How do I bind a DataGrid Width to a converter?

I want to include the size of the VerticalScrollbar when i define the width of a DataGrid.
So far i wrote a Converter:
[ValueConversion(typeof(double), typeof(double))]
public class VerticalScrollbarConverter : IValueConverter
{
#region IValueConverter Member
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is double)
return (double)value + SystemParameters.VerticalScrollBarWidth;
else
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
I included my converter in the xaml namespace with:
xmlns:Core="clr-namespace:Core;assembly=SMS_Core"
And I defined the converter as a (window) resource:
<Window.Resources>
<Core:VerticalScrollbarConverter x:Key="VerticalScrollbarConverter"/>
</Window.Resources>
Since all of my DataGrid.Columns have a fixed Value I know the value that i need to pass.
How do I tell my GridView Width property in xaml to use the converter?
I know that my question is pretty basic. As you can tell I am very new to WPF.
Thanks in advance for every hint. If you need some more info or context just ask away.
The comment from sa_ddam213 didn't exactly solve the problem. But it sure did push me into the right direction.
To pass the value automatically I had to do the following:
I created a property in the window class called TotalColumnWidth. Returning this:
myDataGrid.Columns.Sum(c => c.ActualWidth);
The xaml is the following:
Width="{Binding ElementName=_Root, Path=TotalColumnWidth, Converter={StaticResource ResourceKey=VerticalScrollbarConverter}}"
Using the converter mentioned above.

WPF - Dynamically access a specific item of a collection in XAML

I have a data source ('SampleAppearanceDefinitions'), which holds a single collection ('Definitions'). Each item in the collection has several properties, including Color, which is what I'm interested in here.
I want, in XAML, to display the Color of a particular item in the collection as text. I can do this just fine using this code below...
Text="{Binding Source={StaticResource SampleAppearanceDefinitions}, Path=Definitions[0].Color}"
The only problem is, this requires me to hard-code the index of the item in the Definitions collection (I've used 0 in the example above). What I want to do in fact is to get that value from a property in my current DataContext ('AppearanceID'). One might imagine the correct code to look like this....
Text="{Binding Source={StaticResource SampleAppearanceDefinitions}, Path=Definitions[{Binding AppearanceID}].Color}"
...but of course, this is wrong.
Can anyone tell me what the correct way to do this is? Is it possible in XAML only? It feels like it ought to be, but I can't work out or find how to do it.
Any help would be greatly appreciated!
Thanks!
AT
MultiBinding is your friend here:
Assuming you have a TextBlock:
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource AppearanceIDConverter}">
<Binding Source="{StaticResource SampleAppearanceDefinitions}" />
<Binding Path="AppearanceID" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
And define a MultiValueConverter to return what you wish to see:
public class AppearanceIDConverter : IMultiValueConverter
{
#region IMultiValueConverter Members
public object Convert(object[] values, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
List<item> items = (List<item>)values[0]; //Assuming its items in a List
int id = (int)values[1]; //Assuming AppearanceID is an integer
return items.First(i => i.ID == id).Color; //Select your item based on the appearanceID.. I used LINQ, but a foreach will work just fine as well
}
public object[] ConvertBack(object value, System.Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new System.NotImplementedException();
}
#endregion
}
Of course, you will need to set the converter as a resource in your Resource dictionary, like you did SampleAppearanceDefinitions. You can also ditch the multibinding and use a regular binding to AppearanceID with a IValueConverter, if you can get to the SampleAppearanceDefinitions collection through code ;).
Hope this helps
Even if it could be possible you'd better not do that this way, but instead use a dedicated property in your view model or in the code behind of your view if it has only a pure graphical meaning.
This property, say "CurrentAppearance", would expose a Color property you could bind from your Xaml :
Text="{Binding CurrentAppearance.Color}"
which is more understandable.
As a general advice : avoid to spoil your Xaml with plumbing code : Xaml should be as readable as possible,
particularly if you work with a team of designers that have no coding skills and do not want to be concerned with the way you are managing the data.
Moreover, if later you decide to change the way data are managed you would not have to change your Xaml.
MultiBinding might actually work if your list is on a viewmodel instead of a staticresource. I was suprised myself to see that the object passed on to the view is actually a pointer to the object on the model, so changing the object in the view (eg. typing in new test in the textbox) directly affects the model object.
This worked for me. The ConvertBack method is never useed.
public class PropertyIdToPropertyConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values.Length == 2)
{
var properties = values[0] as ObservableCollection<PropertyModel>;
if (properties != null)
{
var id = (int)values[1];
return properties.Where(model => model.Id == id).FirstOrDefault();
}
}
return null;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}

How to display the text in one line in wpf textblock

I'm a newbie with wpf , what i want to display the text in one line in wpf textblock.
eg.:
<TextBlock
Text ="asfasfasfa
asdasdasd"
</TextBlock>
TextBlock display it in two lines default,
but i want it in only one line like this"asafsf asfafaf". I mean show all the text in one line even there are more than one lines in the text
what should i do?
Use a Converter:
<TextBlock Text={Binding Path=TextPropertyName,
Converter={StaticResource SingleLineTextConverter}}
SingleLineTextConverter.cs:
public class SingleLineTextConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string s = (string)value;
s = s.Replace(Environment.NewLine, " ");
return s;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Instead of this:
<TextBlock Text="Hello
How Are
You??"/>
Use this:
<TextBlock>
Hello
How Are
You??
</TextBlock>
or this:
<TextBlock>
<Run>Hello</Run>
<Run>How Are</Run>
<Run>You??</Run>
</TextBlock>
or set Text property in code behind like this :
(In XAML)
<TextBlock x:Name="MyTextBlock"/>
(In code - c#)
MyTextBlock.Text = "Hello How Are You??"
Code-behind approach has an advantage that you can format your text before setting it.
Example: If the text is retrieved from a file and you want to remove any carriage-return new-line characters you can do it this way:
string textFromFile = System.IO.File.ReadAllText(#"Path\To\Text\File.txt");
MyTextBlock.Text = textFromFile.Replace("\n","").Replace("\r","");

Resources