繁体   English   中英

WPF双向绑定与显式源更新不起作用

[英]WPF two way binding with explicit source updating is not working

我已经绑定了ObservableCollection-DataGrid(模式-TwoWay),但是我想自己通过UpdateSource()调用来更新集合并禁用自动源更新。 我设置像

ItemsSource="{Binding Path=Bezier.BezierPoints, Mode=TwoWay, UpdateSourceTrigger=Explicit}"

但我的收藏集仍会自动更新。 我的代码示例如下。 我究竟做错了什么? 我的XAML:

<DataGrid Name="BezierPointsDataGrid" Margin="5" AutoGenerateColumns="False"
                  Grid.Column="0" Grid.Row="0" Background="White"
                  ItemsSource="{Binding Path=Bezier.BezierPoints, Mode=TwoWay, UpdateSourceTrigger=Explicit}">
            <DataGrid.Columns>
                <DataGridTextColumn Header="X" Binding="{Binding Path=X}" Width="1*"/>
                <DataGridTextColumn Header="Y" Binding="{Binding Path=Y}" Width="1*"/>
            </DataGrid.Columns>
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectionChanged">
                    <i:InvokeCommandAction Command="{Binding Path=UpdateBezierPointsCommand}" CommandParameter="{Binding ElementName=BezierPointsDataGrid}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </DataGrid>

我的ViewModel:

class BezierCurveViewModel : INotifyPropertyChanged
{
    #region Bezier curve model

    private BezierCurveModel _bezier;

    public BezierCurveModel Bezier
    {
        get { return _bezier; }
        set
        {
            if (_bezier == value)
                return;
            _bezier = value;
            OnPropertyChanged("Bezier");
        }
    }

    #endregion

    #region Commands

    public ICommand UpdateBezierPointsCommand { set; get; }

    #endregion 

    #region Constructor

    public BezierCurveViewModel()
    {
        UpdateBezierPointsCommand = new Command(a => ((DataGrid)a).GetBindingExpression(DataGrid.ItemsSourceProperty).UpdateSource());
        Bezier = new BezierCurveModel();
    }

    #endregion

    #region INotifyPropertyChanged implementation

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion
}

我的模特:

public ObservableCollection<DPoint> BezierPoints { private set; get; }

编辑:我将ObservableCollection更改为DataTable,以实现预期的行为。 但是我仍然对解决这个问题感兴趣,因为我想了解为什么在编辑表格后,对可观察集合的任何绑定都会更新源代码(请阅读我对安德鲁发表的评论)。

在这里,您已设置视图以显式更新BezierPoints属性,因为这是您绑定ItemsSource的方式。

我将假设您真正想要的是对各个点的属性使用一个显式更新触发器。 为此,您需要将DataGridTextColum绑定更改为UpdateSourceTrigger = Explicit。

附带说明一下,由于该属性具有私有设置程序,因此根本不可能从View更新BezierPoints集合。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM