I am getting an exception for this binding
<TextBlock.Text>
<MultiBinding Converter="{StaticResource converter}" Mode="OneWay">
<Binding Path="TimeSpanProperty" />
<Binding Path="FormsttingOption" />
</MultiBinding>
</TextBlock.Text>
// converter.Convert code
if (formsttingOption == DurationFormat.Minutes)
return Math.Round(timeSpan.TotalMinutes);
else
return duration;
Value produced by BindingExpression is not valid for target property.; Value='164' MultiBindingExpression:target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')
The converter will, based on formatting option, convert TimeSpan value. In above example, FormattingOption is minutes, which means that TimeSpan value will be converted to minutes (164).
For some reason Text property does not accept this value. Anyone knows the reason, and solution?
I think the error explains it quite nicely:
Value produced by BindingExpression is not valid for target property.; Value='164' MultiBindingExpression:target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')
It tells you that TextBlock.Text is of type String and your converter is not producting a valid value.
In your IMultiValueConverter.Convert method, ensure you are returning a String, i.e.
public object Convert(object[] values, Type targetType, Object parameter, CultureInfo culture)
{
var timeSpan = (TimeSpan)values[0];
var formattingOption = (DurationFormat)values[1];
if(formattingOption == DurationFormat.Minutes)
{
return Math.Round(timeSpan.TotalMinutes).ToString(culture);
}
return duration.ToString(); // TODO not sure where duration comes from
}
Related
I need to create a Converter that takes some value and returns another. This will be used to set the textblock RotateTransform.Angle value in XAML.
If I hard-code the value to a static number the textblock gets rotated successfully. But when it goes through the converter it does not get rotated.
Any insight would be appreciated.
Thanks.
Hard-coded value (works):
<TextBlock ...
<RotateTransform CenterX="0.5" CenterY="0.5">
<RotateTransform.Angle>
10
</RotateTransform.Angle>
</RotateTransform>
Going through a Converter (does not work):
<TextBlock ...
<RotateTransform CenterX="0.5" CenterY="0.5">
<RotateTransform.Angle>
<MultiBinding Converter="{StaticResource RelativeToAbsoluteRotationConverter}">
<Binding Path="RelativeAngle" />
</MultiBinding>
</RotateTransform.Angle>
</RotateTransform>
Converter class:
public class RelativeToAbsoluteRotationConverter: IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
// Add logic here... Function is hit, but no rotation ever takes place.
return 10; // irrelevant
}
// ...
Output window:
System.Windows.Data Error: 5 : Value produced by BindingExpression is not valid for target property. Int32:'30' MultiBindingExpression:target element is 'RotateTransform' (HashCode=57454947); target property is 'Angle' (type 'Double')
The solution is to modify the object Convert() method and instead of returning an int (e.g. 10), we return a double value (e.g. 10d or 10.0).
return 10d; // This works
I need to display TimeSpan in hh:mm format. If negative, there should be a preceding "-".
This is my implementation in the .xaml:
<Label>
<Label.Content>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0:D2}:{1:D2}">
<Binding Path="MyTime.Hours" />
<Binding Path="MyTime.Minutes" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Label.Content>
</Label>
Unfortunately a negative TimeSpan returns both, Hours and Minutes as negative values, resulting in "-07:-12" for example. However, I only need one preceding "-".
Is there a way to check for negativity in the xaml code and then use a datatrigger to put the minus sign?
This custom format string with a section seperator defines sections with separate format strings for positive, negative and zero values (left out the section one for zero values).
<MultiBinding StringFormat="{}{0:D2}:{1:0#;0#}">
<Binding Path="MyTime.Hours"/>
<Binding Path="MyTime.Minutes"/>
</MultiBinding>
This should work - but only when the Hours value is already <= -1:
<MultiBinding StringFormat="{}{0:00}:{1:mm}">
<Binding Path="MyTime.Hours"/>
<Binding Path="MyTime"/>
</MultiBinding>
For showing the minus also for the first (negative) hour, use a Binding Converter like this:
public class TimeSpanConverter : IValueConverter
{
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
var ts = (TimeSpan)value;
var result = ts.ToString(#"hh\:mm");
return ts >= TimeSpan.Zero ? result : "-" + result;
}
public object ConvertBack(
object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
with
<TextBlock Text="{Binding MyTime, Converter={StaticResource TimeSpanConverter}}"/>
I need to display a value in a currency format (EUR / USD / YEN etc.) depending on the currency value stored in the database.
In the database the data is stored like:
Id Value Currency
1 1000 EUR
2 1500 USD
3 9650 USD
In XAML, I'd like to know how I can show the value in a correct currency format.
For example, if I read the first line from the database (Id=1), I like to show it on UI as €1,000 but if I read the second line (Id=2) it should be shown as $1,500.
Right now my XAML MVVM binding looks like this:
<TextBlock Text="{Binding SelectedItem, StringFormat=c0}" ...
...and for me this displays the value always as $1,500 which I do not want.
A converter class can do the trick for you to achieve the desired behavior
public class CurrencyConverter : MarkupExtension, IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return GetCurrency(values);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
private string GetCurrency(object[] values)
{
switch (values[1].ToString())
{
case "USD":
return string.Format(new System.Globalization.CultureInfo("en-US"), "{0:C}", values[0]);
case "EUR":
return string.Format(new System.Globalization.CultureInfo("en-GB"), "{0:C}", values[0]);
default:
return string.Format(new System.Globalization.CultureInfo("en-US"), "{0:C}", values[0]);
}
}
}
Simply use the converter in XAML with your TextBlock bindings.
<TextBlock DataContext="{Binding SelectedItem, ElementName=listBox}">
<TextBlock.Text>
<MultiBinding Converter="{local:CurrencyConverter}">
<Binding Path="Value"/>
<Binding Path="Currency"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
The string format you're using is based on current system locale so it's not a way to go at all. In your situation you would be interested in something like such a converter: http://blogs.msdn.com/b/bencon/archive/2006/05/10/594886.aspx
Pass in two values (currency and amount), return back a string representation to be shown on UI.
I saw in this post a solution that fits exactly my needs https://stackoverflow.com/a/8858815/1462911.
But I don't really know how to properly implement it.
I have for now a PositionConverter which converts coordinates in Strings but i'd like to pass through its parameter the ActualWidth of its Parent (a Canvas).
Does my ConverterHelper have to implement IValueConverter and DependencyObject or just DependencyObject?
I'm a bit lost....
What you need is best accomplished through an IMultiValueConverter and a MultiBinding:
public class PositionConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var scale = (double)values[0]; // this is your [0, 1] double
var max = (double)values[1]; // this is the ActualWidth
return scale * max;
}
}
The binding would look like:
<Element.Property>
<MultiBinding Converter="{StaticResource myConverter}">
<Binding Path="path_to_the_original_double" />
<Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorLevel=1}"
Path="ActualWidth" />
</MultiBinding>
</Element.Property>
I have a GridView that contains a list of files, created dates, and file sizes. Below the grid I have a textblock that says "X Files Selected. Y MB". I can bind to SelectedItems.Count just fine, but can I easily bind to the sum of the file sizes for those that are selected?
The question marks below should be the sum of the SelectedItems fileSize column values. Any ideas?
<TextBlock HorizontalAlignment="Right">
<TextBlock.Text>
<MultiBinding StringFormat=" {0} Files Selected. {1} MB">
<Binding ElementName="FilesList" Path="SelectedItems.Count"></Binding>
<Binding ElementName="FilesList" Path="SelectedItems.?????"></Binding>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
I know I can get this done in the codebehind - but I'd like to keep my codebehind empty and do it in the XAML. This is the codebehind code:
private void FilesList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
double x = 0;
foreach (FileInfo fileInfo in FilesList.SelectedItems)
{
x += fileInfo.Length;
}
}
You're going to have to use a converter for this. An example:
Xaml:
<MultiBinding StringFormat=" {0} Files Selected. {1} MB">
<Binding ElementName="FilesList" Path="SelectedItems.Count"></Binding>
<Binding ElementName="FilesList" Path="SelectedItems" Converter="{StaticResource sumconverter}"></Binding>
</MultiBinding>
Codebehind:
[ValueConversion(typeof(ListViewItem[]), typeof(string))]
class SumConverter : IValueConverter {
public object Convert( object value, Type targetType, object parameter, CultureInfo culture ) {
int size = 0;
ListViewItem[] items = (ListViewItem[])value;
if(items != null){
foreach(var lvi in items){
Someclass sc = lvi.content as Someclass;
if(sc!=null){
size += sc.Size;
}
}
}
return (size / 1000) + "MB";
}
public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture ) {
return null;
}
}
Sadly, you will not be able to do this in XAML, alone.
You will need to bind to the SelectedItems themselves and provide a value converter. The value converter needs to iterate over each file path, create a FileInfo object from the path, and sum up the sizes using the FileInfo.Length property.
You have 3 options.
You can create a sum property in whatever entity you are binding to (your FilesList entity). This will require you to change your FilesList collection to a CollectionView so you can get access to the SelectedItems property from your ViewModel (if you aren't doing this already).
I've never tried this, but you might be able to use Kent Boogaart's "Expression Value Converter" that allows you to write small bits of C#-Like code in your binding expressions: http://wpfconverters.codeplex.com/
Provide a simple ValueConverter that converts a collection of whatever your entity is to a decimal or whatever (this is probably the simplest thing to do).