当WPF中TextBox的焦点丢失时更改StringFormat

问题描述 投票:0回答:1

有一个文本框。我正在为其输入值。并保存它。取回该值时,它将显示为十进制。但是我希望一旦失去文本框的焦点,它就会显示为十进制。

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

因为我需要允许空白文本框,所以我将其作为字符串类型。

  private string _addItem = string.Empty;
    public string AddItem
    {
        get => _addItem;
        set
        {
            if (_addItem != value)
            {
              _addItem = value;
                RaisePropertyChangedEvent("AddItem");
            }
        }
    }
c# wpf focus decimal-point
1个回答
0
投票

让文本框失去焦点时触发添加.00:

在您的VM中:

// Constructor
public YourViewModel()
{
    LostFocusCommand = new DelegateCommand(this.LostFocus);
}

public ICommand LostFocusCommand { get; }

private void LostFocus()
{
    if(decimal.TryParse(addItem, out var dec))
    {
        this.AddItem = dec.ToString("F2"); // or "N2"
    }
}

在您的xaml中,在该特定文本框中添加另一个触发器

<i:EventTrigger EventName="LostFocus" >
    <i:InvokeCommandAction Command="{Binding Path=DataContext.LostFocusCommand, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"  />
</i:EventTrigger>
© www.soinside.com 2019 - 2024. All rights reserved.