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