设置SelectedIndex时,ListBox.SelectedItem绑定被取消

时间:2017-08-01 05:25:56

标签: c# wpf xaml mvvm listbox

我在数据绑定方面遇到了一些问题......以下是这种情况:

我的观点:

<Window x:Class="Shifter.Forms.Employee.frmEditEmployee"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="frmEditEmployee" Height="350.141" Width="497.195" WindowStyle="None" ResizeMode="NoResize" Foreground="Blue" WindowStartupLocation="CenterScreen">        

    <Grid>    
        <ListBox x:Name="lstEmployee" IsEnabled="{Binding NoEditMode}" SelectedItem="{Binding MasterEmployee}" ItemsSource="{Binding Path=ListOfEmployees}" HorizontalAlignment="Left" Height="276" Margin="25,19,0,0" VerticalAlignment="Top" Width="217" />
        <TextBox x:Name="txtForename" Text="{Binding SelectedItem.Forname, ElementName=lstEmployee}" Margin="342,21,0,0" GotFocus="SelectText"/>
        <TextBox x:Name="txtLastname" Text="{Binding SelectedItem.Lastname, ElementName=lstEmployee}" Margin="342,47,0,0" GotFocus="SelectText"/>
        <TextBox x:Name="txtShowingname" Text="{Binding SelectedItem.Showingname, ElementName=lstEmployee}" Margin="342,74,0,0" GotFocus="SelectText"/>
        <TextBox x:Name="txtPersonelNumber" Text="{Binding SelectedItem.EmployeeID, ElementName=lstEmployee}" Margin="342,99,0,0" GotFocus="SelectText"/>
        <DatePicker x:Name="dtpBirthday" SelectedDate="{Binding SelectedItem.Birthday, ElementName=lstEmployee}" HorizontalAlignment="Left" Margin="342,125,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.256,0.417" SelectedDateFormat="Short"/>
        <TextBox x:Name="txtLoan" Text="{Binding SelectedItem.Loan, ElementName=lstEmployee}" Margin="342,151,0,0" TextWrapping="Wrap" GotFocus="SelectText"/>
        <TextBox x:Name="txtPhone" Text="{Binding SelectedItem.Telephone, ElementName=lstEmployee}" Margin="342,229,0,0" TextWrapping="Wrap" GotFocus="SelectText"/>
        <TextBox x:Name="txtEMail" Text="{Binding SelectedItem.EMail, ElementName=lstEmployee}" Margin="342,255,0,0" TextWrapping="Wrap" GotFocus="SelectText"/>
        <ComboBox x:Name="cmbContract" ItemsSource="{Binding ListOfContracts, Mode=TwoWay}" SelectedItem="{Binding SelectedItem.Contract, ElementName=lstEmployee, Mode=TwoWay}" HorizontalAlignment="Left" Margin="342,179,0,0" VerticalAlignment="Top" Width="130"/>
        <ComboBox x:Name="cmbGroup" ItemsSource="{Binding ListOfGroups, Mode=TwoWay}" SelectedItem="{Binding SelectedItem.Group, ElementName=lstEmployee, Mode=TwoWay}" HorizontalAlignment="Left" Margin="342,204,0,0" VerticalAlignment="Top" Width="130"/>
        <CheckBox x:Name="chkHide" Content="MA im Dienstplan ausblenden" IsChecked="{Binding SelectedItem.isHiding, ElementName=lstEmployee}" HorizontalAlignment="Left" Margin="259,280,0,0" VerticalAlignment="Top" ToolTip="Der Mitarbeiter wird nicht im Dienstplan angezeigt (beispielsweise wegen längerer Abwesenheit)" Width="211"/>            

        <Button x:Name="btnAdd" Content="Add" Command="{Binding Path=cmdAdd, Mode=TwoWay}" HorizontalAlignment="Left" Height="35" Margin="25,303,0,0" VerticalAlignment="Top" Width="35">
        </Button>
        <Button x:Name="btnEdit" Content="Edit" Command="{Binding Path=cmdEdit}" HorizontalAlignment="Left" Height="35" Margin="70,303,0,0" VerticalAlignment="Top" Width="35">
        </Button>
        <Button x:Name="btnDelete" Content="Delete" Command="{Binding Path=cmdDelete}" HorizontalAlignment="Left" Height="35" Margin="115,303,0,0" VerticalAlignment="Top" Width="35">
        </Button>
        <Button x:Name="btnCancel" Content="Cancel" Command="{Binding Path=cmdCancel}" HorizontalAlignment="Left" Height="35" Margin="391,303,0,0" VerticalAlignment="Top" Width="35">
        </Button>
        <Button x:Name="btnOK" Content="OK" Command="{Binding Path=cmdOK}" HorizontalAlignment="Left" Height="35" Margin="436,303,0,0" VerticalAlignment="Top" Width="35">
        </Button>
    </Grid>
</Window>

我的ViewModel:

namespace Models
{
    public class VM_EditEmployee : INotifyPropertyChanged
    {
        #region Propertys
        private ObservableCollection<Common.Employee> mListOfEmployees;
        private ObservableCollection<Common.EmployeeContract> mListOfContracts;
        private ObservableCollection<Common.EmployeeGroup> mListOfGroups;
        private Common.Employee mMasterEmployee;
        private bool isNew;
        private Employee.frmEditEmployee EmpoyeeView;

        public event PropertyChangedEventHandler PropertyChanged;

        public ObservableCollection<Common.Employee> ListOfEmployees
        {
            get
            {
                return mListOfEmployees;
            }

            set
            {
                mListOfEmployees = value;
                OnPropertyChanged("ListOfEmployees");
            }
        }
        public ObservableCollection<EmployeeContract> ListOfContracts
        {
            get
            {
                return mListOfContracts;
            }

            set
            {
                mListOfContracts = value;
                OnPropertyChanged("ListOfContracts");
            }
        }
        public ObservableCollection<EmployeeGroup> ListOfGroups
        {
            get
            {
                return mListOfGroups;
            }

            set
            {
                mListOfGroups = value;
                OnPropertyChanged("ListOfGroups");
            }
        }
        public Common.Employee MasterEmployee
        {
            get
            {
                return mMasterEmployee;
            }

            set
            {
                mMasterEmployee = value;
                OnPropertyChanged("MasterEmployee");
            }
        }


        public ICommand cmdAdd { get; set; }
        public ICommand cmdEdit { get; set; }
        public ICommand cmdDelete { get; set; }
        public ICommand cmdCancel { get; set; }
        public ICommand cmdOK { get; set; }

        #endregion

        public VM_EditEmployee(Employee.frmEditEmployee tmpView)
        {
            EmpoyeeView = tmpView;
            cmdAdd = new RelayCommand(o => AddEntry());
            cmdEdit = new RelayCommand(o => EditEntry());
            cmdDelete = new RelayCommand(o => DeleteEntry());
            cmdCancel = new RelayCommand(o => Cancel());
            cmdOK = new RelayCommand(o => SaveEntry());

            ListOfEmployees = Database_Employee.GetListOfEmployee();
            ListOfContracts = Database_Contract.GetListOfContract();
            ListOfGroups = Database_Group.GetListOfGroups();
        }

        protected internal void OnPropertyChanged(string propertyname)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
        }

        private void DeleteEntry()
        {
            if (MessageBox.Show("Sure you want to delete?", "Question", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                Database_Employee.DeleteEmployee(MasterEmployee);
                ListOfEmployees = Database_Employee.GetListOfEmployee();
            }
        }

        private void Cancel()
        {

        }

        private void AddEntry()
        {
            isNew = true;
            Common.Employee newEmployee = new Common.Employee()
            {
                Forname = "Max",
                Lastname = "Mustermann",
                Showingname = "Max",
                EmployeeID = 666,
                Birthday = new System.DateTime(1980, 5, 5),
                Loan = "9,50",
                Contract = Database_Contract.GetListOfContract()[0],
                Group = Database_Group.GetListOfGroups()[0],
                Telephone = "012456789",
                EMail = "chris@roedernet.de",
                isHiding = false
            };

            ListOfEmployees.Add(newEmployee);
            MasterEmployee = newEmployee;
        }

        private void EditEntry()
        {
            isNew = false;
        }

        private void SaveEntry()
        {
                if (isNew == true)
                {
                    Database_Employee.CreateEmployee(MasterEmployee);                    
                }
                else                    {
                    Database_Employee.EditEmployee(MasterEmployee);
                }
                ListOfEmployees = Database_Employee.GetListOfEmployee();
            }
            else // Wenn der EditMode nict aktiv ist
            {
                EmpoyeeView.Close();
            }


        }
    }
}

&#34; MasterEmployee&#34; property用于访问ViewModel中的选定项以保存员工中的更改。 一切正常,ListBox充满了数据,ListBox中所选员工的详细信息在文本框中正确显示(还有更多只有这一个,但对于这个问题不是必需的。)

当我创建一个新员工时,我创建了一个类员工的新实例,用一些占位符信息填充它,并将MasterEmployee的引用设置为这个新员工,因为我想在文本框中编辑新员工风景。然后我编辑新员工,保存更改并希望转到ListView中的其他员工,没有任何反应。我猜是因为当我设置MasterEmployee的引用时,与ListBox的绑定将丢失。

所以我的问题是:我该如何解决这个问题?我想保留MVVM模式,意思是,通过代码设置绑定我需要访问viewmodel中的视图,而不是MVVM。

非常感谢! 克里斯

2 个答案:

答案 0 :(得分:1)

我看到发布的代码有几个问题,可能是因为它不完整:

  • SelectedItem:您的文本框等与SelectedItem绑定,但您的VM上没有此类属性。你可能想要绑定到MasterEmployee。 (注意:我宁愿将SelectedItem命名为)。我认为这是你所看到的根本原因。
  • 当您执行SaveEntry时,您可能完全重新创建列表。因此MasterEmployee不再存在于该列表中。我认为这可能会导致进一步的错误。您正在显示不在列表中的节点。

如果这没有帮助,请提供一个完整的简单示例,因为您发布的代码不完整且无法编译。尽量缩小你的问题范围。

答案 1 :(得分:-1)

问题解决了,这是我的员工类的问题,我已经覆盖了GetHashCode函数以返回employeeID。这会在编辑employeeID时使绑定制动起来...感谢您的努力!