【问题标题】:A good example on how to use UpdateSourceTrigger=Explicit with MVVM关于如何将 UpdateSourceTrigger=Explicit 与 MVVM 一起使用的一个很好的例子
【发布时间】:2012-05-10 16:26:08
【问题描述】:

我正在尝试弄清楚如何使用 UpdateSourceTrigger=Explicit。

我有以下表格:

<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>

我应该调用什么方法来更新User 属性?

我不想通过 x:Name 来处理元素来调用绑定。如果我必须通过 x:Name 来处理元素,就我而言,我也可以完全不绑定。

【问题讨论】:

    标签: c# xaml data-binding mvvm


    【解决方案1】:

    您需要在后面的代码中调用BindingExpression.UpdateSource 来手动更新绑定。显式绑定与 MVVM 并不真正兼容,因为您需要直接引用视图对象来执行手动更新。

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

    【讨论】:

    • 有点晚了,但是如果您只是在代码隐藏中处理按钮单击,事情仍在发生并且仅在视图中相互引用,并且 ViewModel 将仅接收来自绑定的更新通知。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 2012-06-27
    • 2011-08-11
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    相关资源
    最近更新 更多