简体   繁体   中英

Cancel button writes to text box

I have a wpf application that prompts a user to enter some a numeric input for how many seconds to set stale time from a main window. The value is defaulted at 120, if the user wishes to change it he would click on the button and the a new instance of the window would come up and prompt the user to change it, I have the number validation part working, however if the user clicks the cancel button the current value is replaced by a blank(""), empty space, because that is technically the value in enter time window text box. How would I stop this from happening? I just want the window to close the current value to stay what it is. NOTE this also happens if the user enters, say 3, into the box, the default value is replaced with 3 even though the user hit cancel.

Here is the WPF:

<Window x:Class="WpfClient.StaleTimeDialog"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Stale Time" FontFamily="Arial" Width="450" Height="300" Topmost="True" WindowStartupLocation="CenterScreen" ResizeMode="NoResize">
<Grid>
    <Grid.RowDefinitions>
    <RowDefinition Height="Auto"></RowDefinition>
    <RowDefinition Height="Auto"></RowDefinition>
    <RowDefinition Height="Auto"></RowDefinition>
    <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>

    <Label Margin="10" FontSize="16">Enter new Stale Time</Label>

    <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Center" Margin="0, 10, 10, 0">
        <TextBox Name="StaleTime" FontSize="20" Width="150" HorizontalAlignment="Left" VerticalContentAlignment="Center" Text="" AcceptsReturn="False" DataContext="{Binding}" PreviewTextInput="StaleTime_PreviewTextInput"></TextBox>
        <Label Width="Auto" FontSize="20" Height="Auto" VerticalContentAlignment="Center">Seconds</Label>
    </StackPanel>


    <StackPanel Grid.Row="3" HorizontalAlignment="Right" VerticalAlignment="Bottom" Orientation="Horizontal">
        <Button Name="SaveButton" Margin="10,10,10,10" Style="{StaticResource controlButtonStyle}" IsDefault="True" Click="SaveButton_Click">Save</Button>
        <Button Name="CancelButton" Margin="10,10,10,10" Style="{StaticResource controlButtonStyle}" IsCancel="True" Click="CancelButton_Click">Cancel</Button>
    </StackPanel>

</Grid>

Here is the C#:

public partial class StaleTimeDialog : Window
{
    private Client client = null;
    private SystemStatus systemStatus = null;
    private UserTypes userType = UserTypes.Unknown;
    private bool isStandaloneGUI = false;
    private static string CurrentValue = "";

    public StaleTimeDialog()
    {
        InitializeComponent();

        CurrentValue = StaleTime.Text;

    }
    private void Cancel_Click(object sender, EventArgs e)
    {
        StaleTime.Text = CurrentValue.ToString();
        CancelButton.IsCancel = true;
        this.Close();

    }

    private void StaleTime_KeyPress(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            e.Handled = true;


        }
    }
    private void SaveButton_Click(object sender, RoutedEventArgs e)
    {
        if (true)
        {

            this.Close();
        }
        else
        {
            ErrorDialog errorDialog = new ErrorDialog(DialogType.OKDialog, IconType.Warning, "Save failed");

            errorDialog.ShowDialog();
        }
    }
    private void StaleTime_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        CheckIsNumeric(e);
    }

    private void CheckIsNumeric(TextCompositionEventArgs e)
    {
        int result;

        if (!(int.TryParse(e.Text, out result) || e.Text == "."))
        {
            e.Handled = true;
        }
    }

    private void CancelButton_Click(object sender, RoutedEventArgs e)
    {
        this.DialogResult = false;
        StaleTime.Undo();
    }

}

This is the instance where it is called in C#:

    private void EditParametersButton_Click(object sender, RoutedEventArgs e)
    {
        StaleTimeDialog staletimeDialog = new StaleTimeDialog();

        bool? result = staletimeDialog.ShowDialog();

        if (staletimeDialog.StaleTime.Text.Equals("") || staletimeDialog.StaleTime.Text.Equals(" "))
        {
            App.ChipStale = DefaultStaleTime;
        }
        else
        {
            App.ChipStale = Convert.ToInt32(staletimeDialog.StaleTime.Text);
        }
        FoodParametersLine4Run.Text = App.ChipStale.ToString();

    }

You need to bind that TextBox Text property in TwoWay mode to a public property supporting change notification in the DataContext of that View (typically a ViewModel) and set the UpdateSourceTrigger to LostFocus or Explicit .

Once you do that all your problems will disappear and as a bonus you'll get rid of all that ugly code-behind... that's the WPF way of doing things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM