WPF how to bind value to TextBox using MVVM pattern correctness


Marvin Klein

I am currently trying to use WPF. I created a demo project using Windows Template Studio for Visual Studio.

Now I want to add a textbox which should be autosaved by the MVVM pattern. I have added the following XAML in my settings page.

<TextBlock
   Style="{StaticResource BodyTextStyle}"
   Text="Default Page" />
<TextBox Text="{Binding DefaultPage}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="TextChanged">
            <i:InvokeCommandAction Command="{Binding SetDefaultPageCommand}" CommandParameter="{Binding DefaultPage}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</TextBox>

SettingsViewModelI added the following lines to it:

private readonly IDefaultPageService _defaultPageService;
private string _defaultPage;
public ICommand SetDefaultPageCommand => _setDefaultPageCommand ?? (_setDefaultPageCommand = new RelayCommand<string>(OnSetDefaultPage));

public string DefaultPage
{
    get { return _defaultPage; }
    set { Set(ref _defaultPage , value); }
}

private void OnSetDefaultPage(string defaultPage)
{
    _defaultPageService.SetDefaultPage(defaultPage);
}

The service to save is implemented as:

public class DefaultPageService : IDefaultPageService
{
    public DefaultPageService()
    {
    }

    public void InitializeDefaultPage()
    {
        var theme = GetDefaultPage();
        SetDefaultPage(theme);
    }

    public void SetDefaultPage(string defaultPage)
    {
        App.Current.Properties["DefaultPage"] = defaultPage.ToString();
    }

    public string GetDefaultPage()
    {
        if (App.Current.Properties.Contains("DefaultPage"))
        {
            var defaultPage = App.Current.Properties["DefaultPage"].ToString();
            return defaultPage;
        }

        return "https://google.com";
    }

}

Saving the new string works, but unfortunately my command is called before the actual bound property changes its value. I have tried many different TextBox events such as KeyUpand KeyDown. The only event I've found that works, but the GUI fires LayoutUpdatedit again and again , so I'm pretty sure there's a better way.

Does anyone know how I can fix this?

Tan B

The default behavior of a TextBox binding is to update the binding after the TextBox loses focus, so that's why your bind property only changes after the user types, and then does anything to lose focus on the TextBox. You obviously can't use the TextChanged event as it will fire on every keystroke.

The best way to protect your MVVM and rely on the bounds property to change first , is to get rid of your EventTrigger and your ICommand completely, and simply take advantage of when your DefaultPage setter is called.

In your SettingsViewModel:

private readonly IDefaultPageService _defaultPageService;
private string _defaultPage;

public string DefaultPage
{
    get { return _defaultPage; }
    set { Set(ref _defaultPage , value); OnSetDefaultPage(_defaultPage); }
}

private void OnSetDefaultPage(string defaultPage)
{
    _defaultPageService.SetDefaultPage(defaultPage);
}

Related


WPF how to bind value to TextBox using MVVM pattern correctness

Marvin Klein I am currently trying to use WPF. I created a demo project using Windows Template Studio for Visual Studio. Now I want to add a textbox which should be autosaved by the MVVM pattern. I have added the following XAML in my settings page. <TextBlock

WPF how to bind value to TextBox using MVVM pattern correctness

Marvin Klein I am currently trying to use WPF. I created a demo project using Windows Template Studio for Visual Studio. Now I want to add a textbox which should be autosaved by the MVVM pattern. I have added the following XAML in my settings page. <TextBlock

WPF how to bind value to TextBox using MVVM pattern correctness

Marvin Klein I am currently trying to use WPF. I created a demo project using Windows Template Studio for Visual Studio. Now I want to add a textbox which should be autosaved by the MVVM pattern. I have added the following XAML in my settings page. <TextBlock

WPF how to bind value to TextBox using MVVM pattern correctness

Marvin Klein I am currently trying to use WPF. I created a demo project using Windows Template Studio for Visual Studio. Now I want to add a textbox which should be autosaved by the MVVM pattern. I have added the following XAML in my settings page. <TextBlock

How to bind CurrentCell in WPF DataGrid using MVVM pattern

Ballas T I am learning WPF MVVM pattern. I 'm stuck Binding CurrentCell. Basically I need the row index and column index of the current cell.datagrid <DataGrid AutoGenerateColumns="True" SelectionUnit="Cell" CanUserDeleteRows="True"

How to bind StrokeDashArray property in MVVM pattern wpf

some people I have WPF application where I have in a canvas some lines that need to be dashed and some that need to be normal lines. My question is what type exactly is StrokeDashArray. In msdn I see DoubleCollection is used, but from System.Windows.Media. How

How to properly bind a textbox using MVVM

ha007rishnan.n0077 I'm moving my project into MVVM pattern, but the binding is not working. Below is my project code. The problem is that when a new object is created in it, the textbox doesn't update with the value, LRViewModel.csbut a message box pops up say

How to properly bind a textbox using MVVM

ha007rishnan.n0077 I'm moving my project into MVVM pattern, but the binding is not working. Below is my project code. The problem is that when a new object is created in it, the textbox doesn't update with the value, LRViewModel.csbut a message box pops up say

How to bind objects using MVVM design pattern?

La Sabitz I'm trying to change the code below (1.) to the MVVM architecture (2.) but can't figure out how to bind the objects. I think the problem is that the FirstView only passes the value, but not actually the binding object, I have tried a few different ap

How to bind Datagrid using MVVM pattern?

LV98 Target: My current goal is to connect Datagrid and ViewModel. ViewModel currently has code to get data from MySQL. Not sure where to go from here or if I'm doing it right... Technical_Fsqm.xaml <Grid> <TextBlock Text="FSQM"/> <DataGrid x:Name="FSQ

How to bind objects using MVVM design pattern?

La Sabitz I'm trying to change the code below (1.) to the MVVM architecture (2.) but can't figure out how to bind the objects. I think the problem is that the FirstView only passes the value, but not actually the binding object, I've tried a few different appr

How to bind Datagrid using MVVM pattern?

LV98 Target: My current goal is to connect Datagrid and ViewModel. ViewModel currently has code to get data from MySQL. Not sure where to go from here or if I'm doing it right... Technical_Fsqm.xaml <Grid> <TextBlock Text="FSQM"/> <DataGrid x:Name="FSQ

How to bind Datagrid using MVVM pattern?

LV98 Target: My current goal is to connect Datagrid and ViewModel. ViewModel currently has code to get data from MySQL. Not sure where to go from here or if I'm doing it right... Technical_Fsqm.xaml <Grid> <TextBlock Text="FSQM"/> <DataGrid x:Name="FSQ

How to bind Datagrid using MVVM pattern?

LV98 Target: My current goal is to connect Datagrid and ViewModel. ViewModel currently has code to get data from MySQL. Not sure where to go from here or if I'm doing it right... Technical_Fsqm.xaml <Grid> <TextBlock Text="FSQM"/> <DataGrid x:Name="FSQ

How to bind objects using MVVM design pattern?

La Sabitz I'm trying to change the code below (1.) to the MVVM architecture (2.) but can't figure out how to bind the objects. I think the problem is that the FirstView only passes the value, but not actually the binding object, I have tried a few different ap

How to bind Datagrid using MVVM pattern?

LV98 Target: My current goal is to connect Datagrid and ViewModel. ViewModel currently has code to get data from MySQL. Not sure where to go from here or if I'm doing it right... Technical_Fsqm.xaml <Grid> <TextBlock Text="FSQM"/> <DataGrid x:Name="FSQ

How to bind Datagrid using MVVM pattern?

LV98 Target: My current goal is to connect Datagrid and ViewModel. ViewModel currently has code to get data from MySQL. Not sure where to go from here or if I'm doing it right... Technical_Fsqm.xaml <Grid> <TextBlock Text="FSQM"/> <DataGrid x:Name="FSQ

How to bind Datagrid using MVVM pattern?

LV98 Target: My current goal is to connect Datagrid and ViewModel. ViewModel currently has code to get data from MySQL. Not sure where to go from here or if I'm doing it right... Technical_Fsqm.xaml <Grid> <TextBlock Text="FSQM"/> <DataGrid x:Name="FSQ

How to bind value from TextBox to viewmodel in Mvvm Light

Yam I've been working on a sample project with MVVM Light and would like to know how to bind the TextBox Text value and how to pass it between the View model and the View model. This is my first time using MVVM Light, so I'm new to it. Basically, the user will

How to bind value from TextBox to viewmodel in Mvvm Light

Yam I've been working on a sample project with MVVM Light and would like to know how to bind the TextBox Text value and how to pass it between the View model and the View model. This is my first time using MVVM Light, so I'm new to it. Basically, the user will

How to bind value from TextBox to viewmodel in Mvvm Light

Yam I've been working on a sample project with MVVM Light and would like to know how to bind the TextBox Text value and how to pass it between the View model and the View model. This is my first time using MVVM Light, so I'm new to it. Basically, the user will

Bind textbox value to model in WPF

Andrew Simpson I have a wpf application. I have successfully bound listview to ObservableCollections. I now want to do the same with textboxes and I just have a standard class model (no collections). So, I have a static class: namespace MyNameSpace { publi

Bind textbox value to model in WPF

Andrew Simpson I have a wpf application. I have successfully bound listview to ObservableCollections. I now want to do the same with textboxes and I just have a standard class model (no collections). So, I have a static class: namespace MyNameSpace { publi

WPF how to clear textbox content in listview using MVVM

User 584018 I'm using the code below with an MVVM observable, but the "clear" button doesn't clear the content of the textbox. What do I need to do here? mainwindow.xaml <Grid> <Grid.RowDefinitions> <RowDefinition Height="30*"/> <RowDefinit

How to bind command to Window Loaded event using WPF and MVVM

Jason On my WPF window I have a button bound to a command like this: <Button Command="{Binding SearchCommand}"> I want that command to be executed when that window is loaded. I add this to the xaml: Loaded="DXWindow_Loaded"> and I added it to the code-behind

How to bind command to Window Loaded event using WPF and MVVM

Jason On my WPF window I have a button bound to a command like this: <Button Command="{Binding SearchCommand}"> I want that command to be executed when that window is loaded. I add this to the xaml: Loaded="DXWindow_Loaded"> and I added it to the code-behind