How to display the text in one line in wpf textblock - wpf

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","");

Related

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.

Writing conditional statements in XAML code

I have this listBox that gets populated, each item can be either male or female depending on the 'SEX' property that is binded to the listBox. (Could be either 'M' for male and 'F' for female)...
For each item i would like to display either a male or female symbol based on the list items SEX property.
for instance if "{Binding SEX}" equals 'M':
<Image Source="../Images/male48.png" Visibility="Visible" />
and if "{Binding SEX}" equals 'F':
<Image Source="../Images/female48.png" Visibility="Visible" />
How exactly would I go about getting this to work?
A common approach to this problem is to create a value converter, this converts the value returned by a binding into some other value that relates to the property of a UI control.
You can create a converter that takes the sex and maps it to an image source:
public class SexToSourceConverter : IValueConverter
{
public object Convert(object value, string typeName, object parameter, string language)
{
string url = ((string)value == "M") ? "../Images/male48.png" : "../Images/female48.png";
return new BitmapImage(new Uri(url , UriKind.Relative));
}
public object ConvertBack(object value, string typeName, object parameter, string language)
{
throw new NotImplementedException();
}
}
Using it in your XAML as follows:
<Image Source="{Binding Path=Sex, Converter={StaticResource SexToSourceConverter }" />
If someone is interested in how this could work, I've made a solution based on ColinE's answer. First, you've to create a new class which contain the conditions you'll like to add to the XAML code:
public class MyNiceConverterName : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
// Your conditions here!
return value_you_want_to_return; // E.g., a string, an integer and so on
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
throw new NotImplementedException(); // Leave this like here, don't worry
}
}
Call the class whatever you want (right now it's called MyNiceConverterName) and implement the Convert() method with the conditions you'd like to add to the XAML file. Remember to cast the object value to the type you're using (e.g., (int)value if it's an integer).
This is almost done! But not yet, first declare the converter in your XAML as a resource. You can paste this code below the namespaces declaration:
<Control.Resources>
<converter:MyNiceConverterName xmlns:converter="clr-namespace:My_Namespace" x:Key="MyNiceConverterName" />
</Control.Resources>
You've to declare the namespace where you defined the class (i.e., remove My_Namespace with yours') and also rename MyNiceConverterName to your class name. The key will be the name defined to reference the converter within the XAML document, here I've used the same class name but you can freely change it.
Finally, it's time to use the converter. Put this and you're done:
{Binding variable_with_value, Converter={StaticResource MyNiceConverterName}}
Remember to change variable_with_value with the one you'd like to use within your binding.
I hope it helps!
Either use a binding converter or use two triggers.
For Siverlight this is the correct IValueConverter link, I am not sure if triggers are supported.

give a textblock a margin but only if there is content

I have 3 textblocks in a stackpanel in a DataTemplate.
the idea is that the format should be like "a b c" with spaces between the textblocks but it may happen that textblocks "a" and "b" might be empty, so i end up with something like this " c" ( two spaces before textblock c). How can i ensure that i have a margin but only if there is content?
If the TextBlock's Visibility is set to Collapsed, the Margin will not be shown. So I guess you can use a StringToVisibilityConverter to set its Visibility to Collapsed if the Text is empty.
Example
First you need to create a converter like this.
public class StringToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return Visibility.Collapsed;
if (value != null && string.IsNullOrWhiteSpace(value.ToString()))
return Visibility.Collapsed;
return Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Then you need to include this converter into your xaml.
<converters:StringToVisibilityConverter x:Key="StringToVisibilityConverter " />
Finally, use it inside your TextBlock.
<TextBlock x:Name="MyTextBlock" Text="{Binding SomeText}"
Visibility="{Binding SomeText, Converter={StaticResource StringToVisibilityConverter}}" />
For more info regarding how to use a converter, please take a look at this post.
Hope it helps. :)
Add a converter to the Margin and bind it to the Text property. Have the converter sent the margin to a uniform thickness of 0 if the text content is blank.
Put the textblocks in a grid so that their locations are fixed. Add a converter to the martin and bind it to the text property, and if the length of that text is zero, then set the margin to zero.

how to showing time elapsed in a media element in 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);

Bind silverlight combobox to the result of another combobox

I want to do something like this:
<combobox x:Name="cboCustomers" ItemsSource="{Binding Path=Data.Customers}"/>
<combobox x:Name="cboInvoices"ItemsSource="{cboCustomers.SelectedItem.Invoices}"/>
Anyone know of a way to do something like this in Silverlight 3? I am sure there is some information about it out there, but I am having bad luck with Google in forming the question.
You need to specify ElementName on the second binding:
<combobox x:Name="cboCustomers" ItemsSource="{Binding Data.Customers}"/>
<combobox x:Name="cboInvoices"ItemsSource="{Binding SelectedItem.Invoices, ElementName=cboCustomers}"/>
If you also want the second combobox to be disabled until something has been selected in the first combobox you can bind the IsEnabled property of the second combobox to the SelectedItem property of the first combobox through a converter.
Add this class to your project:
public class NullToBooleanConverter : IValueConverter {
public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture) {
if (targetType == typeof(Boolean))
return value != null;
throw new NotSupportedException("Value converter can only convert to Boolean type.");
}
public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture) {
throw new NotSupportedException("Value converter cannot convert back.");
}
}
Add an instance of this class to the resource dictionary of your user control (local is the namespace tag for the namespace of the converter):
<UserControl.Resources>
<local:NullToBooleanConverter x:Key="NullToBooleanConverter"/>
</UserControl.Resources>
Then you can add this to the second combobox:
IsEnabled="{Binding SelectedItem, ElementName=cboCustomers, Converter={StaticResource NullToBooleanConverter}}"
You'd be looking at a Cascading Combobox
http://weblogs.asp.net/manishdalal/archive/2008/10/22/cascading-combobox.aspx

Resources