How do I stop binding properties from updating?

后端 未结 3 1513
长发绾君心
长发绾君心 2021-02-06 01:30

I have a dialog that pops up over the main screen (it\'s actually a user control that appears on the page as per the application demo from Billy Hollis) in my application that h

相关标签:
3条回答
  • 2021-02-06 01:50

    You could use a BindingGroup :

    ...
    <StackPanel Name="panel">
        <StackPanel.BindingGroup>
            <BindingGroup Name="bindingGroup"/>
        </StackPanel.BindingGroup>
        <TextBox Text="{Binding Foo}"/>
        <TextBox Text="{Binding Bar}"/>
        <Button Name="btnSubmit" Content="Submit" OnClick="btnSubmit_Click"/>
        <Button Name="btnCancel" Content="Cancel" OnClick="btnCancel_Click"/>
    </StackPanel>
    ...
    

    Code behind :

    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
        panel.BindingGroup.BeginEdit();
    }
    
    private void btnSubmit_Click(object sender, RoutedEventArgs e)
    {
        panel.BindingGroup.CommitEdit();
        panel.BindingGroup.BeginEdit();
    }
    
    private void btnCancel_Click(object sender, RoutedEventArgs e)
    {
        panel.BindingGroup.CancelEdit();
        panel.BindingGroup.BeginEdit();
    }
    
    0 讨论(0)
  • 2021-02-06 02:02

    Have a look at the Binding.UpdateSourceTrigger property.

    You can set the Binding in your dialog like so

    <TextBox Name="myTextBox" 
        Text={Binding Path=MyProperty, UpdateSourceTrigger=Explicit} />
    

    And then call the UpdateSource method in your button save event

    myTextBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();
    

    Once you've called UpdateSource the source object will be updated with the value from the TextBox

    0 讨论(0)
  • 2021-02-06 02:02

    I also choose to use BindingGroup. But instead of BeginEdit() / CommitEdit() / CancelEdit() pattern I call UpdateSource() explicitly on all the bindings associated with BindingGroup. This approach allows me to add only one event handler instead of 3.

    private void OkButton_Click(object sender, RoutedEventArgs e)
    {
        CommitChanges();
        DialogResult = true;
        Close();
    }
    
    private void CommitChanges()
    {
        foreach (var bindingExpression in this.BindingGroup.BindingExpressions)
        {
            bindingExpression.UpdateSource();
        }
    }
    
    0 讨论(0)
提交回复
热议问题