Home > Enterprise >  XAML set an initial value for a textbox that can also be changed
XAML set an initial value for a textbox that can also be changed

Time:03-16

I have a textbox in my XAML that shows the current working directory. The XAML code looks like this:

<StackPanel x:Name="StackCurrentPath" Orientation="Vertical" Margin="25,25,25,5">
    <StackPanel Orientation="Horizontal" Margin="0,5,0,0">
        <TextBox materialDesign:HintAssist.Hint="Path of app*" materialDesign:HintAssist.HintOpacity="10" materialDesign:HintAssist.Background="White" materialDesign:ValidationAssist.Background="White" materialDesign:HintAssist.Foreground="#FF002655" Style="{StaticResource MaterialDesignOutlinedTextFieldTextBox}" x:Name="txtboxCurrentPath" Width="230" TextChanged="txtboxCurrentPath_TextChanged">
            <Binding Path="CurrentPath" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay" Source="{StaticResource MyConfigurations}" >
                <Binding.ValidationRules>
                    <local:PathValidation ValidatesOnTargetUpdated="True"/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox>
    </StackPanel>
</StackPanel>

The code behind looks like this:

public partial class PathSection: Page
{
    private string currentDirectoryPath = System.AppDomain.CurrentDomain.BaseDirectory;
    public PathSection()
    {
        var currentDir = System.IO.Path.GetFullPath(System.IO.Path.Combine(currentDirectoryPath, @"..\Assets\"));
    }
    InitializeComponent();
    txtboxCurrentPath.Text = currentDir;

    private void txtboxCurrentPath_TextChanged(object sender, RoutedEventArgs e)
    {
        //some code here for binding the value to MyConfigurations.CurrentPath
    }
}

I am trying to make it so that initially, the textbox should display the path on its own but the user can still make changes to it if they want. The problem I have is that when I do make changes and when I navigate back to this page, the components are reinitialized and the path that the user had changed gets overwritten. How can I make it so that the initial value is current path on its own however the user can still change and it won't get overwritten when they come back?

CodePudding user response:

change

txtboxCurrentPath.Text = currentDir;

to

txtboxCurrentPath.Text = string.IsNullOrEmpty(MyConfigurations.CurrentPath) ? currentDir : MyConfigurations.CurrentPath;

but I think your design is not correct

  • Related