currency textbox on wpf c# - c#

i dont know how to make my textbox from string to currency. I already do search on STO, google. but don't understand how to use it.
let's say i have one textbox.
whenever it run the program, i key in inside the textbox.
if i key in 1000, i want my textbox automatically change to 1,000.
if i key in 10000, my textbox will looks like 10,000.
but whenever i key in 100, my textbox will still 100.
here is my textbox xaml.
<TextBox Height="25" HorizontalAlignment="Left" Margin="126,223,0,0" Name="txtPrice"
VerticalAlignment="Top" Width="140" PreviewTextInput="txtPrice_PreviewTextInput" />
I ever done this before using vb.net, but now i'm using wpf. still new to wpf.
any idea how to that? thanks.

Try this:-
<Style TargetType="{x:Type TextBox}">
<Setter Property="Text" Value="{SomeValue, StringFormat=C}" />
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="Text" Value="{SomeValue, UpdateSourceTrigger=PropertyChanged}" />
</Trigger>
</Style.Triggers>
</Style>

Use the StringFormat dependency property to format the way you want the string to be shown on UI. Try this -
<TextBox Text="{Binding YourBinding, StringFormat='##,#',
UpdateSourceTrigger=PropertyChanged}"/>
For more formats refer to this link from msdn - Custom Numeric Format

Related

How to remove a dictionary resource reference from a TextBlock?

I have this element:
<TextBlock Style="{StaticResource textReplyMessageStyle}">
<Run x:Name="answerMessage" Text="{Binding Message, Mode = OneWay, FallbackValue = ''}" />
</TextBlock>
And I have the need to print in answerMessage either the content of the var Message (thanks to the binding) or an element from the dictionary (thanks to resource reference done by the code below).
answerMessage.SetResourceReference(Run.TextProperty, "Answer_Message_Not_Selected");
The binding is fully working as well as the dictionary reference, but after setting the resource reference once I can not find a way to make the binding work again.
I tried to re-do the binding programmatically but is not working...
The only working workaround I found is to set programmatically the text of answerMessage.
How can I remove the resource reference from the Run element and make the binding work again?
Just to give a bit of context the variable Message contains a number and the resource Answer_Message_Not_Selected
contains the text "Not selected" or a translation in a different language depending on the dictionary active on the program. I have to use dynamic resource reference because the language of the program can be changed on the fly.
Thanks!
A simple way to work this around is to make the output of the TextBlock depends mainly on the Message property.
For example, you can bind the value of Text to Message only if the value of Message is not null, otherwise set it to your resource:
<TextBlock Style="{StaticResource textReplyMessageStyle}">
<Run x:Name="answerMessage" >
<Run.Style>
<Style TargetType="{x:Type Run}">
<Setter Property="Text" Value="{Binding Message, Mode = OneWay, FallbackValue = ''}" />
<Style.Triggers>
<DataTrigger Binding="{Binding Message}" Value="{x:Null}">
<Setter Property="Text" Value="{StaticResource Answer_Message_Not_Selected}" />
</DataTrigger>
</Style.Triggers>
</Style>
</Run.Style>
</Run>
</TextBlock>
Notice that you should set the starting value of Text inside the style because properties set in the control initializer will override any style setters!
Another thing you can do instead of setting the value of Message to null is to add a property AnswerMessageSelected in the view model, to be more explicit when the TextBlock should change its target value:
<TextBlock Style="{StaticResource textReplyMessageStyle}">
<Run x:Name="answerMessage" >
<Run.Style>
<Style TargetType="{x:Type Run}">
<Setter Property="Text" Value="{Binding Message, Mode = OneWay, FallbackValue = ''}" />
<Style.Triggers>
<DataTrigger Binding="{Binding AnswerMessageSelected}" Value="False">
<Setter Property="Text" Value="{StaticResource Answer_Message_Not_Selected}" />
</DataTrigger>
</Style.Triggers>
</Style>
</Run.Style>
</Run>
</TextBlock>
And generally after using this method, it might not be necessary to use x:Name to refer to in the code behind, since it's a better practice to let the ViewModel do all the work and not the code behind the View:
<TextBlock>
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource textReplyMessageStyle}">
<Setter Property="Text" Value="{Binding Message, Mode = OneWay, FallbackValue = ''}" />
<Style.Triggers>
<DataTrigger Binding="{Binding AnswerMessageSelected}" Value="False">
<Setter Property="Text" Value="{StaticResource Answer_Message_Not_Selected}" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
My initial suspicions were correct, thanks to #Jason Tyler #o_w for confirming that.
When you set a reference to a Run (and also for similar elements) you lose the binding property.
The solution to my problem is simply to do the binding again.
Binding b = new Binding();
b.Path = new PropertyPath("Message");
b.Source = this;
BindingOperations.SetBinding(answerMessage, Run.TextProperty, b);
This solution fixes the problem, but it is possible to fix the cause by setting the Answer_Message_Not_Selected resource to the bonded Message element.
Message = Application.Current.Resources["Answer_Message_Not_Selected "].ToString()
If the resource is dynamic, like in my case, you will need some sort of OnChange event observing the resource (or dictionary) to keep the content of Message always updated.

Can I change the color of the text of my property when using mvvm?

I'm new here, so if there's anything I'm doing wrong or need to do differently, I'd love to hear it.
I have a property error message that I "binded" with the xmal. This property returns 2 strings. Either a message that something hasn't been entered or a calculation.
Can I give red with one and black with the other?
Thank you in advance,
this is the method
Property
xmal
You can use a DataTrigger inside a Style for the label.
<Label x:Name="lblFoutmelding" FontWeight="SemiBold" Content="{Binding Foutmelding" Grid.Row="3" Height="30" Margin="9 10 0 0">
<Label.Style>
<Style TargetType="Label">
<Setter Property="Foreground" Value="Black"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Foutmelding}" Value="Gelieve de hoeveeleed in ta geven aub!">
<Setter Property="Foreground" Value="Red"/>
</DataTrigger>
</Style.Triggers>
<Style>
</Label.Style>
</Label>
Note that I have removed the black into a style setter, since setting it directly on the Label would override any style or trigger setters.
Also note that it would be much better to have a separate "Severity" property in your VM and trigger on that, rather than triggering on specific strings.

WPF: Show Tooltip message on custom DataGrid cells when IDataErrorInfo

I'm pretty new to WPF but I've read a lot on it as well as MVVM in the last couple if days.
My WPF displays a DataGrid with custom column templates (using the NumericUpDown Controls from Xceed WPF Toolkit). Three of the columns contain the decimal coordinates of a 3D vector. I use IDataErrorInfo to make sure the vector's length is never 0 (all three columns cannot be 0 at the same time). This is working fine so far, the cells are marked red when the validation fails, but I also want to show the error message in a tooltip or similar.
<DataGrid [...]>
<DataGrid.Columns>
[...]
<DataGridTemplateColumn Header="X" [...]>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<xctk:DecimalUpDown Value="{Binding PositionX, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True}">
</xctk:DecimalUpDown>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
[... and same thing for Y and Z]
</DataGrid.Columns>
</DataGrid>
This is where I'm stuck for a few hours now, so I hope you can help me here:
How can I show a error tooltip on custom template columns?
I've read through a lot of articles and threads on error tooltips but most of them are on plain TextBox or DataGridTextColumns and a tried a lot but could not make it working so far.
Most of them look something like this:
<Style x:Key="errorStyle" TargetType="{x:Type TextBox}">
<Setter Property="Padding" Value="-2"/>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="Background" Value="Red"/>
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
from here:
https://msdn.microsoft.com/library/ee622975%28v=vs.100%29.aspx
or more exsamples:
Display validation error in DataGridCell tooltip
https://stackoverflow.com/a/7900510/5025424
https://harishasanblog.blogspot.de/2011/01/datagrid-validation-using.html
WPF data validation and display error message IDataErrorInfo and error templates
Nothing on this ever showed any Tooltip to me.
Can you give me a hint,
how this style trigger definition has to look for cells containing no TextBox,
where the definition has to be
and if the column needs the reference this definition in some way?
Thank you!
Set the Style property of the control to a Style with a trigger that sets the Tooltip property of the control in the CellTemplate if the attached Validation.HasError property returns true:
<DataGridTemplateColumn Header="X">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<xctk:DecimalUpDown Value="{Binding PositionX, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True}">
<xctk:DecimalUpDown.Style>
<Style TargetType="xctk:DecimalUpDown">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip" Value="{Binding (Validation.Errors)[0].ErrorContent, RelativeSource={RelativeSource Self}}" />
</Trigger>
</Style.Triggers>
</Style>
</xctk:DecimalUpDown.Style>
</xctk:DecimalUpDown>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Having trouble setting visibility of control through DataTemplates

So, I'm building an order tracking app with different user accounts, some of whom have less need-to-know than others. This means that certain controls are displayed for some accounts, and hidden for others.
The datacontext for the Window is set to my Order class, and the data binding within the text fields works perfectly in regards to displaying properties from the specific Order. However, the DataTemplates and Triggers I've made don't seem to be doing anything at all, and I'm not entirely sure why. I've looked all over the web and I can't seem to find why it's not working. Here's the XAML:
<Label Name="StatusLabelText" Content="Status:" FontSize="15" DockPanel.Dock="Top">
<Label.Resources>
<DataTemplate DataType="x:Type local:Order">
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=selectedAccount}" Value="Color Correct">
<Setter Property="Visibility" Value="Hidden"></Setter>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</Label.Resources>
</Label>
I suspect you want to hide label in case selectedAccount value is Color Correct.
You need Style to do that and not a template if my assumption is correct which can be done like this:
<Label Name="StatusLabelText" Content="Status:" FontSize="15"
DockPanel.Dock="Top">
<Label.Style>
<Style TargetType="Label">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=selectedAccount}"
Value="Color Correct">
<Setter Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Label.Style>
</Label>
On a side note, you should use Collapsed instead of Hidden to set visibility of control in case you don't want the label to take the size even when it's not visible on GUI. Read more about it here.

Create WPF Watermark in Pure XAML

This is for a TextBox control on a login screen, where the TextBox contains the username. I want the TextBox to perform in the following way:
When the content is empty the content should be set to "Username".
When the TextBox is clicked I want the content to be set to
"" i.e; nothing (unless the content has already been edited by the user).
This is a pretty standard feature nowadays, something like this wordpress login (at the top of page). coudn't think of a better example than this I'm afraid :)
So, anyway, I've already done this using a ViewModel and it works well, but I'd like to know if this can be done purely from the XAML end. No business logic is concerned so I think it would be better to do it without the VM.
Find the below samples help you to find your way.
http://bendewey.wordpress.com/2008/09/27/wpf-shadowed-textbox-watermark/
http://www.c-sharpcorner.com/uploadfile/rahul4_saxena/watermark-textbox-in-wpf/
http://www.codeproject.com/Articles/26977/A-WatermarkTextBox-in-3-lines-of-XAML
Pure XAML:
<Grid>
<TextBox Width="250" VerticalAlignment="Center" HorizontalAlignment="Left" x:Name="SearchTermTextBox" Margin="5"/>
<TextBlock IsHitTestVisible="False" Text="Enter Search Term Here" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="10,0,0,0" Foreground="DarkGray">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Text, ElementName=SearchTermTextBox}" Value="">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Grid>
Taken from: https://stackoverflow.com/a/21672408/4423545
The Extended WPF Toolkit has a Watermark Textbox that will do just what you're asking in pure XAML. There are other libraries out there as well.
The good thing about using the Extended WPF Toolkit is you can pick it up on Nuget and install and install updates directly through Visual Studio.

Categories