Search code examples
c#wpffocusdecimal-point

Change the StringFormat when the focus from TextBox is lost in WPF


There is a TextBox. I am entering a value to it. and saving it. When fetching back the value it is displayed as decimal. But I want it to be displayed as decimal once the focus of the textbox is lost.

<DataGridTemplateColumn Header="Add-Item" Width="2.25*">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBox Text="{Binding AddItem ,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay,StringFormat=N2}"  Margin="6,5,4,5" helpers:TextBoxExtension.ValidationType="DecimalSpecialCharacter">
                            <i:Interaction.Triggers>
                                <i:EventTrigger EventName="PreviewKeyUp" >
                                    <i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"  />
                                </i:EventTrigger>
                            </i:Interaction.Triggers>

                        </TextBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

As I need to allow blank textbox I am taking it as string type.

  private string _addItem = string.Empty;
    public string AddItem
    {
        get => _addItem;
        set
        {
            if (_addItem != value)
            {
              _addItem = value;
                RaisePropertyChangedEvent("AddItem");
            }
        }
    }

Solution

  • Have the textbox to trigger adding .00 when it loses the focus:

    In your VM:

    // Constructor
    public YourViewModel()
    {
        LostFocusCommand = new DelegateCommand(this.LostFocus);
    }
    
    public ICommand LostFocusCommand { get; }
    
    private void LostFocus()
    {
        if(decimal.TryParse(addItem, out var dec))
        {
            var rounded = Math.Round(dec, 2); // round to 2 decimals
            this.AddItem = rounded.ToString("F2"); // or "N2"
        }
    }
    

    In your xaml add another trigger in that particular textbox

    <i:EventTrigger EventName="LostFocus" >
        <i:InvokeCommandAction Command="{Binding Path=DataContext.LostFocusCommand, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"  />
    </i:EventTrigger>