C# ObservableCollection未更新我的GridViewColumns(MVVM)

C# ObservableCollection未更新我的GridViewColumns(MVVM),c#,wpf,mvvm,binding,gridviewcolumn,C#,Wpf,Mvvm,Binding,Gridviewcolumn,嗨,有人能帮忙吗?我有一个ListView,它绑定到一个ObservableCollection,即StabCollection。数据显示得非常完美 我有两个文本框和一个组合框,使用户可以编辑列。当编辑这些文本框时,gridview中的值会按预期进行更改,但是我正在尝试实现一个取消功能,以将更改恢复到原始状态。手动更改StabCollection的SelectedItem或更改StabCollection[SelectedIndex]不会更新UI,但集合正在更改。任何帮助都将不胜感激

嗨,有人能帮忙吗?我有一个ListView,它绑定到一个ObservableCollection,即StabCollection。数据显示得非常完美

我有两个文本框和一个组合框,使用户可以编辑列。当编辑这些文本框时,gridview中的值会按预期进行更改,但是我正在尝试实现一个取消功能,以将更改恢复到原始状态。手动更改StabCollection的SelectedItem或更改StabCollection[SelectedIndex]不会更新UI,但集合正在更改。任何帮助都将不胜感激

     <Window.DataContext>
    <local:MoveStabViewModel/>
</Window.DataContext>
<StackPanel>
    <Menu IsEnabled="{Binding ListViewEnabled}">
        <MenuItem Header="File"/>             
        <MenuItem Header="Add" Command="{Binding AddCommand}"/>
        <MenuItem Header="Delete"/>           
    </Menu>
    <StackPanel Orientation="Horizontal">
        <ListView ItemsSource="{Binding StabCollection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsEnabled="{Binding ListViewEnabled}" SelectedIndex="{Binding SelectedIndex}" SelectedItem="{Binding SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="10"  >
            <ListView.Resources>
                <Style TargetType="TextBlock">
                    <Setter Property="HorizontalAlignment" Value="Center"/>

                </Style>
                <Style TargetType="GridViewColumnHeader">
                    <Setter Property="HorizontalAlignment" Value="Center"/>
                    <Setter Property="Margin" Value="5"/>
                    <Setter Property="Padding" Value="5"/>
                </Style>
            </ListView.Resources>
            <ListView.View>
                <GridView>
                    <GridViewColumn DisplayMemberBinding="{Binding Position}" Width="Auto" Header="Position (m)"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Type}" Width="Auto" Header="Type"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Pot}" Width="Auto" Header="Tip (mV)"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Current}" Width="Auto" Header="Current (mA)"/>
                    <GridViewColumn DisplayMemberBinding="{Binding CurrentDensity}" Width="Auto" Header="Current Density (mA/m2)"/>
                    <GridViewColumn DisplayMemberBinding="{Binding FieldGradient}" Width="Auto" Header="Field Gradient (uV/cm)"/>
                </GridView>
            </ListView.View>
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="MouseDoubleClick">
                    <i:InvokeCommandAction Command="{Binding EditCommand}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </ListView>
        <GroupBox Header="Edit Stabs" Width="Auto" Visibility="{Binding IsEdit, Converter={StaticResource BoolToVisConverter }}">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <Label Content="Position" Grid.Column="0" Grid.Row="0"/>
                <Label Content="Contact Type" Grid.Column="0" Grid.Row="1"/>
                <Label Content="Potential" Grid.Column="0" Grid.Row="3"/>
                <TextBox Text="{Binding SelectedItem.Position, Mode=TwoWay}" Grid.Row="0" Grid.Column="1"/>
                <ComboBox x:Name="PrintOutComboBox" ItemsSource="{Binding PrintOut}" Width="220" SelectedItem="{Binding SelectedItem.Type, Mode=TwoWay}"                         
                      Grid.Row="1" Grid.Column="1">
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="SelectionChanged">
                            <i:InvokeCommandAction Command="{Binding ButtonOneCommand}"/>
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </ComboBox>
                <ComboBox SelectedIndex="{Binding ElementName=PrintOutComboBox, Path=SelectedIndex}" Width="{Binding ElementName=PrintOutComboBox ,Path=Width}"
                      ItemsSource="{Binding LongPrintOut}" Grid.Row="2" Grid.Column="1"/>
                <TextBox Text="{Binding SelectedItem.Pot, Mode=TwoWay}" Grid.Row="3" Grid.Column="1"/>
                <UniformGrid Grid.Row="4" Grid.ColumnSpan="2" Columns="2">
                    <Button Content="{Binding ButtonOne}" Command="{Binding ButtonOneCommand}"/>
                    <Button Content="Cancel" Command="{Binding CancelCommand}"/>
                </UniformGrid>
            </Grid>
        </GroupBox>
    </StackPanel>
</StackPanel>


public class MoveStabViewModel : INotifyPropertyChanged, IDialogRequestClose
{
    ChartEditViewModel VM;
    List<AnnotationFile> annotation;

    private void OnPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    string[] _printOut;
    public string[] PrintOut
    {
        get { return _printOut; }
        set { _printOut = value; }
    }

    string[] _longPrintOut;
    public string[] LongPrintOut
    {
        get { return _longPrintOut; }
        set { _longPrintOut = value; }
    }

    private string[] SplitCommaDelimitedString(string value)
    {
        string[] splitString = value.Split(',');
        return splitString;
    }

    ObservableCollection<StabTypes> stabTypes;
    public ObservableCollection<StabTypes> StabTypes { get { return stabTypes; } }

    public MoveStabViewModel()
    {

    }

    public MoveStabViewModel(ChartEditViewModel VM)
    {
        this.VM = VM;
        annotation = VM.annotation;
        PrintOut = new string[21];
        LongPrintOut = new string[21];
        stabTypes = new ObservableCollection<StabTypes>();

        for (int i = 0; i < 20; i++)
        {
            PrintOut[i] = VM.printOut[i + 1];
            LongPrintOut[i] = VM.printLongName[i + 1];
            stabTypes.Add(new StabTypes { Code = PrintOut[i], Description = LongPrintOut[i] });
        }

        EditCommand = new ActionCommand(p => LstContactsDoubleClick());
        CancelCommand = new ActionCommand(p => Cancel());
        ButtonOneCommand = new ActionCommand(p => ButtonOneMethod());
        AddCommand = new ActionCommand(p => Add());
        LoadStabs();
    }

    private void ButtonOneMethod()
   {
        if (ButtonOne == "Add Stab")
        {               

        }
        else
        {
            //StabCollection[SelectedIndex].Position = SelectedItem.Position;
            //StabCollection[SelectedIndex].Pot = SelectedItem.Pot;
            //StabCollection[SelectedIndex].Type = DisplayStab;

        }
    }

    private void Add()
    {
        SelectedItem = null;
        DisplayStab = "";
        ListViewEnabled = false;
        if (SelectedItem != null)
        {
            DisplayStab = SelectedItem.Type;
        }
        else
        {
            DisplayStab = "";
        }
        ButtonOne = "Add Stab";
        WindowSize += 342;
    }

    public List<string[]> TempAnno { get; set; }

    private ObservableCollection<AnnotationBreakDown> _stabBreakdown = new ObservableCollection<AnnotationBreakDown>();
    public ObservableCollection<AnnotationBreakDown> StabCollection
    {
        get { return _stabBreakdown;}
        set { _stabBreakdown = value; OnPropertyChanged("StabCollection"); }
    }

    public ICommand EditCommand { get; }
    public ICommand CancelCommand { get; }
    public ICommand AddCommand { get; }
    public ICommand ButtonOneCommand { get; }

    public event EventHandler<DialogCloseRequestedEventArgs> CloseRequested;
    public event PropertyChangedEventHandler PropertyChanged;

    public void LoadStabs()
    {
        var annotationFile = new AnnotationFile();                      

        int j = 0;
        for (int i = 0; i < annotation.Count; i++)
        {
            if (annotation[i]._type == "E")
            {
                var tempStringArray = SplitCommaDelimitedString(annotation[i]._anno);
                int stabType = annotationFile.EvalStabType(Strings.Mid(annotation[i]._anno, 1, 1));

                bool potCorrectFormat = float.TryParse(tempStringArray[0].Substring(1, 5), out float pot);
                bool currentCorrectFormat = float.TryParse(tempStringArray[1], out float current);
                bool cdCorrectFormat = float.TryParse(tempStringArray[2], out float cd);
                bool fgCorrectFormat = float.TryParse(tempStringArray[3], out float fg);
                bool mcCorrectFormat = float.TryParse(tempStringArray[4], out float mc); //McCoy Current
                bool mcCDCorrectFormat = float.TryParse(tempStringArray[5], out float mcd);
                bool mcFGCorrectFormat = float.TryParse(tempStringArray[6], out float mfg);


                StabCollection.Add(new AnnotationBreakDown());

                StabCollection[j].Position = Strings.Format(annotation[i]._KP, "#####0.0");
                StabCollection[j].Type = VM.printOut[stabType];
                if (potCorrectFormat) StabCollection[j].Pot = pot;
                if (currentCorrectFormat) StabCollection[j].Current = current;
                if (cdCorrectFormat) StabCollection[j].CurrentDensity = cd;
                if (fgCorrectFormat) StabCollection[j].FieldGradient = fg;
                if (mcCorrectFormat) StabCollection[j].MC = mc;
                if (mcCDCorrectFormat) StabCollection[j].MCD = mcd;
                if (mcFGCorrectFormat) StabCollection[j].MFG = mfg;

                j += 1;
            }

        }
    }

    //Are we editing the stabs?
    private bool _listviewEnabled = true;
    public bool ListViewEnabled
    {
        get { return _listviewEnabled; }
        set { _listviewEnabled = value; OnPropertyChanged("ListViewEnabled"); }
    }

    //The selected item from listview
    private AnnotationBreakDown _selectedItem = new AnnotationBreakDown();
    public AnnotationBreakDown SelectedItem
    {
        get { return _selectedItem; }
        set { _selectedItem = value; OnPropertyChanged("SelectedItem"); }
    }

    private string _displayStab;
    public string DisplayStab
    {
        get { return _displayStab; }
        set { _displayStab = value; OnPropertyChanged("DisplayStab"); }
    }

    //The listview Selected Index
    int _selectedIndex;
    public int SelectedIndex
    {
        get { return _selectedIndex; }
        set { _selectedIndex = value;  OnPropertyChanged("SelectedIndex"); }
    }

    //Property to store Add/Accept Button 
    private string _buttonOne = "Accept";

    public string ButtonOne
    {
        get { return _buttonOne; }
        set { _buttonOne = value; OnPropertyChanged("ButtonOne"); }
    }

    string tempPos;
    string tempType;
    float tempPot;

    //Event called when mouse is double clicked on listview
    public void LstContactsDoubleClick()
    {
        if (SelectedItem == null) return;

        tempPos = StabCollection[SelectedIndex].Position;
        tempType = StabCollection[SelectedIndex].Type;
        tempPot = StabCollection[SelectedIndex].Pot;

        ListViewEnabled = false;
        DisplayStab = SelectedItem.Type;

        WindowSize += 342;
    }

    //Dynamic Window Size CLR property
    private int _windowSize = 610;
    public int WindowSize
    {
        get { return _windowSize; }
        set { _windowSize = value; OnPropertyChanged("WindowSize"); }
    }       


    public void Cancel()
    {
        ListViewEnabled = true;
        SelectedItem.Type = "GP";

        WindowSize -= 342;
    }

}
public class StabTypes
{
    public string Code { get; set; }
    public string Description { get; set; }

    public string CodeToolTip
    {
        get { return Description; }
    }


}
public class AnnotationBreakDown
{
    public string Position { get; set; }
    public string Type { get; set;}
    public float Pot { get; set; }
    public float Current { get; set; }
    public float CurrentDensity { get; set; }
    public float FieldGradient { get; set; }
    public float MC { get; set; } //McCoy Current
    public float MCD { get; set;} //McCoy CD
    public float MFG { get; set; } //McCoy FG
}

公共类MoveStabViewModel:INotifyPropertyChanged,IDialogreeQuestClose
{
ChartEditViewModel虚拟机;
列表注释;
私有void OnPropertyChanged([CallerMemberName]字符串propertyName=”“)
{
PropertyChanged?.Invoke(这是新的PropertyChangedEventArgs(propertyName));
}
字符串[]_打印输出;
公共字符串[]打印输出
{
获取{return\u printOut;}
设置{u printOut=value;}
}
字符串[]长打印输出;
公共字符串[]长打印输出
{
获取{return\u longPrintOut;}
设置{u longPrintOut=value;}
}
私有字符串[]SplitCommaDelimitedString(字符串值)
{
string[]splitString=value.Split(',');
返回splitString;
}
可观察收集类型;
公共ObservableCollection StabTypes{get{return StabTypes;}}
public MoveStabViewModel()
{
}
public MoveStabViewModel(ChartEditViewModel虚拟机)
{
this.VM=VM;
annotation=VM.annotation;
打印输出=新字符串[21];
LongPrintOut=新字符串[21];
stabTypes=新的ObservableCollection();
对于(int i=0;i<20;i++)
{
打印输出[i]=VM.PrintOut[i+1];
LongPrintOut[i]=VM.printLongName[i+1];
Add(新的stabTypes{Code=PrintOut[i],Description=LongPrintOut[i]});
}
EditCommand=newactionCommand(p=>LstContactsDoubleClick());
CancelCommand=newActionCommand(p=>Cancel());
ButtonOneCommand=新操作命令(p=>ButtonOneMethod());
AddCommand=newactionCommand(p=>Add());
LoadStabs();
}
私有方法()
{
如果(按钮否==“添加刺”)
{               
}
其他的
{
//StabCollection[SelectedIndex].Position=SelectedItem.Position;
//StabCollection[SelectedIndex].Pot=SelectedItem.Pot;
//StabCollection[SelectedIndex].Type=DisplayStab;
}
}
私有void Add()
{
SelectedItem=null;
DisplayStab=“”;
ListViewEnabled=false;
如果(SelectedItem!=null)
{
DisplayStab=SelectedItem.Type;
}
其他的
{
DisplayStab=“”;
}
ButtonOne=“添加刺”;
WindowSize+=342;
}
公共列表节拍{get;set;}
private ObservableCollection _Thankreakdown=新ObservableCollection();
公共可观测集合
{
获取{return}
设置{u sthorreakdown=value;OnPropertyChanged(“StabCollection”);}
}
公共ICommand EditCommand{get;}
公共ICommand CancelCommand{get;}
公共ICommand AddCommand{get;}
公共ICommand按钮命令{get;}
请求的公共事件事件处理程序;
公共事件属性更改事件处理程序属性更改;
公共void LoadStabs()
{
var annotationFile=新的annotationFile();
int j=0;
for(int i=0;i    public class ItemsChangeObservableCollection<T> :
           System.Collections.ObjectModel.ObservableCollection<T> where T : INotifyPropertyChanged
    {
        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                RegisterPropertyChanged(e.NewItems);
            }
            else if (e.Action == NotifyCollectionChangedAction.Remove)
            {
                UnRegisterPropertyChanged(e.OldItems);
            }
            else if (e.Action == NotifyCollectionChangedAction.Replace)
            {
                UnRegisterPropertyChanged(e.OldItems);
                RegisterPropertyChanged(e.NewItems);
            }

            base.OnCollectionChanged(e);
        }

        protected override void ClearItems()
        {
            UnRegisterPropertyChanged(this);
            base.ClearItems();
        }

        private void RegisterPropertyChanged(IList items)
        {
            foreach (INotifyPropertyChanged item in items)
            {
                if (item != null)
                {
                    item.PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged);
                }
            }
        }

        private void UnRegisterPropertyChanged(IList items)
        {
            foreach (INotifyPropertyChanged item in items)
            {
                if (item != null)
                {
                    item.PropertyChanged -= new PropertyChangedEventHandler(item_PropertyChanged);
                }
            }
        }

        private void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            //launch an event Reset with name of property changed
            base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }
    }
}


    private ItemsChangeObservableCollection<AnnotationBreakDown> _stabBreakdown = new ItemsChangeObservableCollection<AnnotationBreakDown>();
    public ItemsChangeObservableCollection<AnnotationBreakDown> StabCollection
    {
        get { return _stabBreakdown;}
        set { _stabBreakdown = value; }
    }
public class AnnotationBreakDown : INotifyPropertyChanged
{
    public string Position { get; set; } // To raise PropertyChanged 
    public string Type { get; set;} // To raise PropertyChanged 
    public float Pot { get; set; } // To raise PropertyChanged 
    public float Current { get; set; } // To raise PropertyChanged 
    public float CurrentDensity { get; set; } // To raise PropertyChanged 
    public float FieldGradient { get; set; } // To raise PropertyChanged 
    public float MC { get; set; } //McCoy Current
    public float MCD { get; set;} //McCoy CD
    public float MFG { get; set; } //McCoy FG
}