Good example of how to use UpdateSourceTrigger = Explicit with MVVM

I am trying to figure out how to use UpdateSourceTrigger = Explicitly.

I have the following form:

<StackPanel x:Name="LayoutRoot" Margin="10" DataContext="{Binding ElementName=Window, Mode=OneWay}">
    <DockPanel>
        <TextBlock Text="Proxy address:" VerticalAlignment="Center"/>
        <TextBox Text="{Binding User.PageAddress, Mode=TwoWay, UpdateSourceTrigger=Explicit}" Margin="28,0,0,0"/>
    </DockPanel>
    <DockPanel Margin="0,5,0,0">
        <TextBlock Text="User name:" VerticalAlignment="Center"/>
        <TextBox Text="{Binding User.UserName, Mode=TwoWay, UpdateSourceTrigger=Explicit}" Margin="46,0,0,0"/>
    </DockPanel>
    <DockPanel Margin="0,5,0,0">
        <TextBlock Text="User password:" VerticalAlignment="Center"/>
        <TextBox Text="{Binding  User.Password, Mode=TwoWay, UpdateSourceTrigger=Explicit}" Margin="26,0,0,0"/>
    </DockPanel>
    <StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,5,0,0">
        <Button Content="Ok" IsDefault="True" Width="70" Margin="0,0,15,0" Click="Ok_Click"/>
        <Button Content="Cancel" IsCancel="True" Width="70"/>
    </StackPanel>
</StackPanel>

What method should I call to update the property User?

I do not want to access the elements with x: Name in order to invoke the binding. If I need to address elements by x: Name, I can also go without binding as far as I know.

+5
source share
1 answer

You need to call BindingExpression.UpdateSource in the code to manually update the binding. Explicit binding is not really compatible with MVVM, since you need to directly reference view objects in order to perform a manual update.

// itemNameTextBox is an instance of a TextBox
BindingExpression be = itemNameTextBox.GetBindingExpression(TextBox.TextProperty);
be.UpdateSource();
+9

All Articles