Arsen Zahray
Arsen Zahray

Reputation: 25347

A good example on how to use UpdateSourceTrigger=Explicit with MVVM

I'm trying to figure out how to use UpdateSourceTrigger=Explicit.

I've got 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 User property?

I don't want to address the elements by x:Name to invoke the binding. If I have to address the elements by x:Name, I as well can go without binding altogether, as far as I'm concerned.

Upvotes: 6

Views: 9977

Answers (1)

shf301
shf301

Reputation: 31404

You need to call BindingExpression.UpdateSource in the code behind to manually update the binding. Explicit binding isn't really compatible with MVVM since you need to directly reference the view objects to perform the manually update.

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

Upvotes: 11

Related Questions