Why file path not shown in text field after FilePicker picks up file? (Razor MAUI)

67 views Asked by At

I have the code in .razor like below. After I pick up the file, the input field will not show the path immediately. But if I click the button again, the path shows up suddenly. How can I change the codes?

<div>

    <label for="inputdata">Input Data:</label>
    <input type="text" name="inputdata" value="@filePath" />
    <button @onclick="OpenFileAsync">Open</button>

</div>

@code {

    private string filePath;

    public async void OpenFileAsync()
    {
        var customFileType = new FilePickerFileType(
            new Dictionary<DevicePlatform, IEnumerable<string>>
                {
                { DevicePlatform.WinUI, new[] { "jpg" } },
                }
        );

        PickOptions options = new()
        {
            PickerTitle = "Please select a comic file",
            FileTypes = customFileType,
        };
        var result = await FilePicker.Default.PickAsync(options);
        if (result != null)
        {
            filePath = result.FullPath;
        }
    }
}
1

There are 1 answers

0
Liqun Shen-MSFT On BEST ANSWER

You could use StateHasChanged method to notify the component that its state has changed.

Just add this piece of code after filepath has been changed,

public async void OpenFileAsync()
{
    ...
    var result = await FilePicker.Default.PickAsync(options);
    if (result != null)
    {
        filePath = result.FullPath;
    }
    // add this code
    StateHasChanged();
}

Hope it helps!