WPF databinding to display number in an appropriate currency - wpf

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.

Related

Binding 2 textboxes with calculated ratio

I have a model that contains a HorsePower and a Kilowatt property
1 HP = 0.745 KW
I then have 2 textboxes where i want to update 'the other' with the calculated value.
eg: if i input '100' into the bound HP textbox, i want the KW textbox to update with '74,5'
and vise versa : 74,5 into KW -> updates HP to 100
one solution i figured, would be to bind to only 1 property, eg: HP and then use a value converter for the KW textbox (and then update KW on property changed)
is there another way to do this ?
You will need a binding converter like this:
public class MinusValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
return 100 - System.Convert.ToInt32(value);
}
catch (Exception)
{
return null;
}
}//END Convert
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}//END ConvertBack
}//END class ValueToCurrentConverter : IValueConverter
And XAML:
<TextBox Name="tbHorsepower" Text="8"/>
<TextBox Text="{Binding ElementName=tbHorsepower, Path=Text, Converter={StaticResource SubstractFrom100}}" IsReadOnly="True">
<TextBox.Resources>
<local1:MinusValueConverter x:Key="SubstractFrom100"/>
</TextBox.Resources>
</TextBox>
(Your textboxes will most likely look different)

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)

Add extra column to WPF DataGrid which is not in the collection

I'm using a DataGrid control to display content of a DataTable. Therefore the data table is set as ItemsSource of DataGrid.
Following columns of the DataGrid represent columns of the data table:
Type, Name, Domain, Subdomain
Now the dynamic column, called "Properties" should contain specific information, depending on the value of the "Type" column.
Something like this:
switch (Type)
case ABC: content="row.Field1"
case DEF: content="row.Field2"
case XYZ: content="row.FieldX"
Where Field1 .. FieldX are all columns from the data table.
I'm currently using a DataGrid together with a BindingListCollectionView.
Best if the solution would build up on this.
I tried with multivalue binding and a multivalue converter but I would like to have more freedom and not having to pre-select the fields:
var bind = new MultiBinding();
bind.Bindings.Add(new Binding("Protocol"));
bind.Bindings.Add(new Binding("Path1"));
bind.Bindings.Add(new Binding("Path2"));
bind.Bindings.Add(new Binding("Path3"));
bind.Bindings.Add(new Binding("Path4"));
bind.Converter = _ConfigurationMultiValueConverter;
col.Binding = bind;
You could use something like that. Of course it's only an example.
public class YourClass
{
public YourType Protocol;
public YourType2 Path1;
public YourType3 Path2;
public YourType4 Path3;
public YourType5 Path4;
public int ChooseExpression;
public YourType6 Field1;
public YourType7 Field3;
public YourType8 FieldX;
}
and then in your DataGrid
<DataGrid Name="IfYouNeedAName" AutoGennerateColumn="False" ItemsSource={Binding YourClass} >
<DataGrid.Columns>
<DataGridTextColumn Header="ProtocolHeader" Binding={Binding Protocol} />
<DataGridTextColumn Header="Path1Header" Binding={Binding Path1} />
...
<DataGridTextColumn Header="TheChoosenOne" Binding={Binding YourClass, YourBindingConverer} />
</DataGrid.Columns>
</DataGrid>
and at last the converter, which inherit by IValueConverter
public class YourBindingConverer : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
switch(value.ChooseExpression)
case 1: return Field1.ToString();
case 2: return Field3.ToString();
case 3: return FieldX.ToString();
else
return string.Empty;
end;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
I've wrote it from my memory, becasue I don't have VS here. But I think, it could be something like that.
If you have more questions, feel free to ask.
And for bonus, here is good solution for value converters.

Empty textbox bound with some decimal value

I have a textbox bound to some decimal value. Now, if I type something in it like 100 and clear it completely (empty). I save the data and it saves 1 in decimal value. Similarly if I tried 200 and clear textbox it saves 2. Remember decimal value is not null. Any ideas?
<TextBox
Height="23"
VerticalAlignment="Center"
Text="{Binding Discount,Mode=TwoWay}"
MaxLength="50"
TabIndex="28"
Grid.Row="2"
Grid.Column="1"
local:FocusExtension.IsFocused=
"{Binding Path=IsDiscountFocused,Mode=TwoWay}"
Margin="5,0,0,0"/>
Since String.Empty cannot be converted into a decimal per default. The last valid value is kept in the property.
You should use a converter as below.
Wpf
<Window.Resources>
<local:ValueConverter x:Key="valueConverter" />
</Window.Resources>
<TextBox Text="{Binding Path=Value, Mode=TwoWay, Converter={StaticResource valueConverter}}" />
Converter:
public class ValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is string && (string)value == "")
{
return 0;
}
return value;
}
}
Clr:
public decimal Value
{
get { return (decimal)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
i assume that your Discount property in your viewmodel looks like:
public decimal Discount {get;set;}
if you use backspace and clear your textbox you get a binding exception because "" can not convertet to decimal. so the last number remains in your property. actually this should happen when using UpdateSourceTrigger=Propertychanged. but nevertheless you can try using decimal?. if this not help you can also add a converter to convert the "" to a value your viewmodel can handle.
EDIT: i did not see you last comment. but in the case you want a 0 for an empty textbox, just use a converter to return 0 when "" is the input.

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