WPF: is it possible to send to convert another object? [duplicate] - wpf

So i have simple Gauge class with static int property that implement Propertychanged:
TotalPacketsSent
This property is raising all the time and i want to wrote simple converter and send this converter this property value and return some value base on this property:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int val = (int)value;
double percentage = ((double)MyClass.TotalPacketsSent / MyClass.TotalPacketsInList) * 100;
return percentage;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Under Window.Resources i have this:
<Convertors:GaugeValueConverter x:Key="GaugeValueConverter"/>
And this is my Gause:
<Controllers:Gauge x:Name="gauge"
Value="{Binding Path=(my:MyClass.TotalPacketsSent), Converter={StaticResource GaugeValueConverter}}"
Minimum="0"
Maximum="100"/>
So my issue is that my converter not working at all, i mean that i cannot see that this even executed.
Any ideas why ?
Edit:
This property is changing all the time and i have Label i am using this way to show its value:
Content="{Binding Path=(my:MyClass.TotalPacketsSent)}"
And this works fine.

You're casting the value argument as an int and then not using it.
I imagine what you're looking for is something like (deriving from IMultiValueConverter rather than IValueConverter):
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
double totalPacketsSent = (double)values[0];
double totalPacketsInList = (double)values[1];
// further validation for handling divide by zero, etc. may need to go here
return totalPacketsSent / totalPacketsInList * 100
}
And in the XAML:
<Controllers:Gauge x:Name="gauge" Minimum="0" Maximum="100">
<Controllers:Gauge.Value>
<MultiBinding Converter="{StaticResource GaugeValueConverter}">
<Binding Path="(my:MyClass.TotalPacketsSent)" />
<Binding Path="(my:MyClass.TotalPacketsInList)" />
</MultiBinding>
</Controllers:Gauge.Value>
</Controllers:Gauge>

Related

WPF stringformat show only digital

i want in wpf application show only decimal number in a textblock.
I have for example "35.56", i want show only ".56"
Thank you
You can represent 0.56 as only .56 using <TextBlock Text="{Binding Path=yourprop, StringFormat='#.##'}" /> but 35.56 cannot be represented using .56 using a StringFormat because 35.56 and .56 are two different values.
If you want to represent 35.56 as .56 for some strange reason, you'd better format the string using some custom logic in your view model:
public string YourPropFormatted
{
get
{
string s = yourprop.ToString("#.00", CultureInfo.InvariantCulture);
int index = s.IndexOf('.');
return (index > 0) ? s.Substring(index) : s;
}
}
XAML is a markup language and can't handle this.
Complementing mm8 answer with another way to get the same result is implementing a IValueConverter.
public class NumberToDecimalPartConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if(!(value is double val))
return default(double).ToString(); // or ".00", you decide
string s = val.ToString("#.00", CultureInfo.InvariantCulture);
int index = s.IndexOf('.');
return index > 0 ? s.Substring(index) : s;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// you don't need convert back
throw new NotImplementedException();
}
}
Assuming the converter is placed at same namespace
<Window.Resources>
<local:NumberToDecimalPartConverter x:Key="NumberToDecimalPart"/>
</Window.Resources>
<TextBlock Text="{Binding Path=yourprop, Converter={StaticResource NumberToDecimalPart}}" />
When your property changes, the UI will be updated, right?
With converter, you have one more step that is convert the value.
So what I'm doing here it's when the property (your probably double value) change, the WPF will call the Convert function from NumberToDecimalPartConverter. When the property have Mode setted as TwoWay will call ConvertBack.

How to fire Property Set for Textboxes bound to numeric data

I just noticed that WPF textboxes bound to numeric data do not fire Property Set when non-numeric events happen such as letters/spaces typed or text cleared. This becomes a problem when I'm trying to validate that a textbox has a valid number. If the user types in 5 and presses backspace, the databound property remains 5 while the textbox appears empty! I have no way of disabling a button to stop further progress. Is there anyway to enable non-numeric notifications when bound to numeric data? Or, am I forced to use a string property/data converter? Thanks.
If you do not like the default converter you need to create your own which returns a valid value if the input is empty or unparsable.
public class IntBindingConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string input = value as string;
if (String.IsNullOrWhiteSpace(input))
{
return 0;
}
else
{
int outInt;
if (int.TryParse(input, out outInt))
{
return outInt;
}
else
{
return 0;
}
}
}
}
Example usage:
<TextBox>
<TextBox.Text>
<Binding Path="Max">
<Binding.Converter>
<vc:IntBindingConverter/>
</Binding.Converter>
</Binding>
</TextBox.Text>
</TextBox>
This may look a bit messy but normally you in fact just stop the user from proceeding.

How perform calculation on a XAML Binding value: reverse it, multiply it, subtract from it or add to it?

First; the question is rhetorical, I have an answer! I have gotten so much help from looking here that I wanted to give this neat trick back.
Imagine that you have a value that you want to bind to, but it is somehow or somewhat wrong.
I had a situation where I wanted to bind to a value, but when the value was 1, I needed 0, and vice-versa.
There was a time when I wanted to bind the width of an element to the width of a parent - 68px.
Enter the FirstDegreeFunctionConverter:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
namespace GenericWPF
{
/// <summary>
/// Will return a*value + b
/// </summary>
public class FirstDegreeFunctionConverter : IValueConverter
{
public double A { get; set; }
public double B { get; set; }
#region IValueConverter Members
public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
double a = GetDoubleValue( parameter, A );
double x = GetDoubleValue( value, 0.0 );
return ( a * x ) + B;
}
public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
double a = GetDoubleValue( parameter, A );
double y = GetDoubleValue( value, 0.0 );
return ( y - B ) / a;
}
#endregion
private double GetDoubleValue( object parameter, double defaultValue )
{
double a;
if( parameter != null )
try
{
a = System.Convert.ToDouble( parameter );
}
catch
{
a = defaultValue;
}
else
a = defaultValue;
return a;
}
}
How to use it?
You make a resource for each use in the resource section:
<GenericWPF:FirstDegreeFunctionConverter x:Key="ReverseOne"
A="-1"
B="1" />
<Border Opacity="{Binding Path=Opacity
, ElementName=daOtherField
, Converter={StaticResource ReverseOne}}" />
<GenericWPF:FirstDegreeFunctionConverter x:Key="ListboxItemWidthToErrorWidth"
A="1"
B="-68" />
<TextBox MaxWidth="{Binding Path=ActualWidth
, Converter={StaticResource ListboxItemWidthToErrorWidth}
, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}" />
The name comes from the function y = a*x + b (Called a "first degree function" in Norwegian), and of course it would be possible to upgrade it to a second degree function y= a*x^2 + bx + c, but I haven't found a use for it yet.
I had a situation where I wanted to make columns based on width. Each time I got 200 pixels more width, I wanted the container to show me another column. At that time I hardcoded a converter, but I should have made a y=(a/x) + b converter instead.
Now, what should I have named this converter so that everybody understand what it is? Since I'm a Norwegian, I used the expression we learned in school, directly translated. Please, if you have a suggestion or an opinion, let me know.
Any refinements or improvements you have thought of would also be appreciated...
Maybe "LinearTransformConverter" would better communicate what the converter does for you, I'll think about it.
Any other proposals?
Tor
What is even better is a PolynomialConverter, here's the one-way version:
public class PolynomialConverter : IValueConverter
{
public DoubleCollection Coefficients { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double x = (double)value;
double output = 0;
for (int i = Coefficients.Count - 1; i >= 0 ; i--)
output += Coefficients[i] * Math.Pow(x, (Coefficients.Count - 1) - i);
return output;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//This one is a bit tricky, if anyone feels like implementing this...
throw new NotSupportedException();
}
}
Examples:
<!-- x^2 -->
<vc:PolynomialConverter Coefficients="1,0,0"/>
<!-- x + 5 -->
<vc:PolynomialConverter Coefficients="1,5"/>
<!-- 2x + 4 -->
<vc:PolynomialConverter Coefficients="2,4"/>
Alternatively one could use the ConverterParameter instead to not set the Coefficients in the converter itself.
DoubleCollection coefficients = DoubleCollection.Parse((string)parameter);
//...

Order of execution in a WPF Textbox

I'm running into an issue with a formatting converter and data validation. I have the following textbox XAML declaration
<TextBox FontFamily="Segoe" FontSize="16" FontWeight="Medium"
TabIndex="{Binding TabBinding}" Foreground="Black"
Opacity="0.9" IsTabStop="True" Uid="{Binding PriceID}"
Text="{Binding NewPrice,Converter={StaticResource FormattingConverter},
ConverterParameter=' \{0:C\}', Mode=TwoWay, UpdateSourceTrigger=LostFocus}"
Background="#FFE6DED3" BorderBrush="#FFE6DED3"
DataContext="{Binding StringFormat=\{0:c\}, NotifyOnValidationError=True}"
Padding="0" KeyDown="TextBox_KeyDown" AcceptsReturn="False">
</TextBox>
The issue I'm up against is a data validation issue. When a user enters an invalid price (Ex: a value of "abc" or "0.0.4"), the textbox attempts to perform the conversion in the "FormattingConverter" method. (ConvertBack method pasted below) This causes an exception and the program errors out. Is there a way to delay the FormattingConverter call or bypass it if the data in the textbox is not valid?
public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var objTypeConverter = System.ComponentModel.TypeDescriptor.GetConverter(targetType);
object objReturnValue = null;
if (objTypeConverter.CanConvertFrom(value.GetType())) {
objReturnValue = objTypeConverter.ConvertFrom(value.ToString().Replace("$", ""));
}
return objReturnValue;
}
Thank you,
A converter's ConvertBack always runs to convert the data to a value suitable for the target object. It is the responsibility of the converter to handle exceptions (and in the case of exception, return the original value so the binding framework will also realize it's an invalid value).
public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var objTypeConverter = System.ComponentModel.TypeDescriptor.GetConverter(targetType);
// Default return value is the original value - if conversion fails, return
// this value so the binding framework will see an invalid value (and not
// just null).
object objReturnValue = value;
if (objTypeConverter.CanConvertFrom(value.GetType())) {
try {
objReturnValue = objTypeConverter.ConvertFrom(value.ToString().Replace("$", ""));
}
catch( FormatException ) { }
// Catch all of your possible exceptions and ignore them by returning the original value
}
return objReturnValue;
}
You can also return DependencyProperty.UnsetValue, however in practice I prefer to see the actual error message returned in validation from an invalid value than to simply return an unset value.

WPF Textblock Convert Issue

am usina text block in usercontrol, but am sending value to textblock from other form, when i pass some value it viewed in textblock, but i need to convert the number to text. so i used converter in textblock. but its not working
<TextBlock Height="21" Name="txtStatus" Width="65" Background="Bisque" TextAlignment="Center" Text="{Binding Path=hM1,Converter={StaticResource TextConvert},Mode=OneWay}"/>
converter class
class TextConvert : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
if (value.ToString() == "1")
{
return value = "Good";
}
if (value.ToString() == "0")
{
return value = "NIL";
}
}
return value = "";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return (string)value;
}
}
is it right? whats wrong in it??
ok I think I know what the problem is - let see if I can define it for you :)
in your xaml file where you want to use TextConvert, define Resource for it (unless you are doing it already, then I haven't a clue why its not working)
<Grid.Resources>
<Shared:TextConvert x:Key="TextConvertKey" />
</Grid.Resources>
shared being the xmlns ofcourse.
Then in the textbox use it like:
Text="{Binding Path=hM1,Converter={StaticResource TextConvertKey},Mode=OneWay}"/>
EDIT:
If you set a breakpoint in the converter class, does the debugger go in there?????
EDIT 2:
am using like this voodoo
local:HealthTextConvert x:Key="TextConvert"
This is absolutely wrong. How can you Call it HealthTextConvert when the converter name is TextConvert???
it should be
local:TextConvert x:Key="whateverKeyNameYouWant"
and
in the textbox is should be
Text="{Binding Path=hM1,Converter={StaticResource whateverKeyNameYouWant},Mode=OneWay}"
I can see immediately a problem with your converter definition.
class TextConvert : IValueConverter
{
...
Should be declared public to be able to use it as a resource.
public class TextConvert : IValueConverter
{
...
Also, its not a good thing to be doing this...
return value = "Good";
...
return value = "NIL";
It should just be (even though it will not matter if you leave it, just bad programming =P):
return "Good";
...
return "Nill";
Try by removing Path in the below line
Text="{Binding **Path**=hM1,Converter={StaticResource TextConvert},Mode=OneWay}".
Sometimes it works without Path :).
Also look into the output window(Alt+Cntl+O)...to see where the issue is.

Resources