How can I bind RotateTransform.Angle value via a Converter? - wpf

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

Related

How to bind int to Visibility in WPF?

I have BudgetControlType Properties that has 1 .. 7 value
if(BudgetControlType ==1)
dataComboBox1.Visibility=Visibility.Visiblile;
dataComboBox2 to dataComboBox7 =Visibility.Hidden;
if(BudgetControlType ==2)
dataComboBox1.Visibility=Visibility.Visiblile;
dataComboBox2.Visibility=Visibility.Visiblile;
dataComboBox3 to dataComboBox7 =Visibility.Hidden;
and so on...
How to do this in xaml?
Here is another approach I have used in the past using WPFConverters.
<TabItem.Visibility>
<Binding Path="SomeObservableCollection.Count">
<Binding.Converter>
<converters:ConverterGroup>
<converters:ExpressionConverter Expression="{}{0} > 0" />
<BooleanToVisibilityConverter />
</converters:ConverterGroup>
</Binding.Converter>
</Binding>
</TabItem.Visibility>
The ConvertGroup allows for multiple converters to be run sequentially.
The ExpressionConverter lets you define an arbitrary expression. In my case I want the TabItem to be visible if the collection count is greater than zero. Being defined in xaml means escaping characters and a somewhat awkward syntax but it works well enough!
The BooleanToVisibilityConverter converts the boolean result from the expression to our desired visibility.
For Elham, BudgetControlType could be bound to as long as it implemented INotifyPropertyChanged. An equals expression is done like this (I'm returning true if the bound value equals 7):
<converters:ExpressionConverter Expression="{}{0} == 7" />
You can use 1,2,4,8,... and convert it to Visibility
for example if your int number is 6 (2+4) then Control with paramerter 2 and Control with parameter 4 is Visible!
public class IntToVisibilityConverter:IValueConverter
{
private int val;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int intParam = (int)parameter;
val = (int)value;
return ((intParam & val) != 0) ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
And in xaml :
<ComboBox Visibility="{Binding Path=MyEnum,UpdateSourceTrigger=PropertyChanged, Converter={StaticResource IntToVisibilityConverter}, ConverterParameter=1}"/>
<ComboBox Visibility="{Binding Path=MyEnum,UpdateSourceTrigger=PropertyChanged, Converter={StaticResource IntToVisibilityConverter}, ConverterParameter=2}"/>
<ComboBox Visibility="{Binding Path=MyEnum,UpdateSourceTrigger=PropertyChanged, Converter={StaticResource IntToVisibilityConverter}, ConverterParameter=4}"/>
The best way I'd say would be to go with properties on your ViewModel, and bind to them.
example (you'll have to massage it a bit, but it's fairly simple from here) :
public Visibility dtcb1 { get; set; }
// all the rest till 7
// Somewhere in your logit / constructor :
dtcb1 = BudgetControlType == 1 ? Visible : Hidden;
// and so on
And on your xaml you'll bind your visibility to dtcb1
You can make the property boolean, and use a boolean to visibility converter as well (as per this answer for example, or just google yourself)

Formatting a negative TimeSpan

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}}"/>

Binding to TimeSpan field with IMultiValueConverter

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
}

wp create a Converter with a binded ConverterParameter

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>

Binding to a sum of SelectedItems in WPF GridView

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).

Resources