UI未使用更新进行更新 [英] UI not updating with update

查看:96
本文介绍了UI未使用更新进行更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我是wpf的新手,我们在wpf上有一个项目,所以我的带领让我学习并做了一些poc和一些我如何用Google搜索并开始学习

当我设计一个mvvm应用程序时

我有列表通过datcontext有源和绑定网格到该源,当我点击更新时我有一个更新按钮我为此更新了更新的代码,但是一旦我关闭了一个drun应用程序,我在UI.please帮助中获得了旧值。



我已经护目镜并找到了一些不同的解决方案。请帮助我发现有点理解。



我的代码我喜欢:

查看型号:

Hi,
I am new to the wpf and we got one project on wpf so my lead asked me to study and do a poc and some how I googled and started to learn
when I designed a mvvm application
I have list has source and binding grid to that source through datcontext ,I had an update button when I click update I am geeting the updated vale for that ,but once I close an drun the applicaton I am getting the old values In UI.please help.

I have goggled and found some different different solutions.Please help I am finding a bit diificult in understanding.

My code I s like:
view model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dataapplication.Model;
using System.Windows.Input;
using System.Windows;
using Dataapplication.View;
using System.ComponentModel;

namespace Dataapplication.ViewModel
{
    class ViewModelTest 
 
    {
         //When the user clicks a button in the View, a command on the ViewModel executes to perform the requested action
        private IList<Employee> _UsersList;
        private ICommand _mUpdater;//nned to be created while performing any command in view model which is used for defining a command ** here it is for UPDATE**
        private ICommand _command;//  ** here it is for REMOVE**
       

        public ViewModelTest()
        {
            _UsersList = new List<Employee>
             {
                 new  Employee{EmployeeNumber=1,FirstName="Raj",LastName="hari",Department="Depo",Title="INDIA"},
                 new  Employee{EmployeeNumber=2,FirstName="Mark",LastName="henry",Department="Natural Science",Title="USA"},
                 new  Employee{EmployeeNumber=3,FirstName="Mahesh",LastName="Chand",Department="Physics",Title="USA"},
                 new  Employee{EmployeeNumber=4,FirstName="Vikash",LastName="Nanda",Department="Biology",Title="INDIA"},
                 new  Employee{EmployeeNumber=5,FirstName="Harsh",LastName="Kumar",Department="History", Title="INDIA"},
                 new  Employee{EmployeeNumber=6,FirstName="Reetesh",LastName="Tomar",Department="English", Title="INDIA"},
                 new  Employee{EmployeeNumber=7,FirstName="Deven",LastName="Verma",Department="Physical Educataion", Title="INDIA"},
                 new  Employee{EmployeeNumber=8,FirstName="Ravi",LastName="Taneja",Department="Police", Title="INDIA"}            
             };


        }



        //private void Button_Click(object sender, RoutedEventArgs e)
        //{
        //    txtFirstName.GetBindingExpression(TextBox.TextProperty).UpdateSource();
        //    txtLastName.GetBindingExpression(TextBox.TextProperty).UpdateSource();
        //    txtPrice.GetBindingExpression(TextBox.TextProperty).UpdateSource();
        //}

        public IList<Employee> Users
        {
            get { return _UsersList; }
            set { _UsersList = value; }
        }

        
       
        public ICommand UpdateCommand
        {
            get
            {
                if (_mUpdater == null)
                    _mUpdater = new Updater();
                return _mUpdater;
            }
            set
            {
                _mUpdater = value;
            }
        }

        public ICommand RemoveCommand
        {
            get
            {
                if (_command == null)
                {
                    _command = new Remover(CanExecute, Execute);
                }
                return _command;
            }


        }  //willl be binded to grid 

        private void Execute(object parameter)
        {
            int index = Users.IndexOf(parameter as Employee);
            if (index > -1 && index < Users.Count)
            {
                Users.RemoveAt(index);
            }
        }

        private bool CanExecute(object parameter)
        {
            return true;
        }

        //**CanExecute and Execute are delegate commands which are used in MVVM  to enables the user to hook up UI interactions with code without tightly coupling with two.
        //Those two are called ICommand Members

        private class Updater : ICommand
        {
            public bool CanExecute(object parameter)
            {
                return true;
            }

            public event EventHandler CanExecuteChanged;

            public void Execute(object parameter)
            {

            }

        }


        private class Remover : ICommand
        {
            Predicate<object> canExecute;
            Action<object> execute;

            public Remover(Predicate<object> _canexecute, Action<object> _execute)
                : this()
            {
                canExecute = _canexecute;
                execute = _execute;
            }

            public Remover()
            {
            }

            public bool CanExecute(object parameter)
            {
                return canExecute == null ? true : canExecute(parameter);
            }

            public event EventHandler CanExecuteChanged;

            public void Execute(object parameter)
            {
                execute(parameter);
            }

        }

    }
}





我的观点是:



my view is:

<Window x:Class="Dataapplication.View.testdata1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DataApplication" Height="300" Width="300" SizeToContent="WidthAndHeight" 
ResizeMode="NoResize">

    <Grid>
        <Grid Margin="0,0,0,20">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

<!--<ListView Name="ListViewProducts" Grid.Row="1" Margin="4,109,12,23"  ItemsSource="{Binding Path=Products}" SelectedItem="{Binding SelectedProduct}" >-->
            <ListView Name="UserGrid" Grid.Row="1" Margin="4,178,12,13"  ItemsSource="{Binding Users, Mode=TwoWay}"  >
                <ListView.View>
                    <GridView x:Name="grdTest">
                        <GridViewColumn Header="EmployeeNo" DisplayMemberBinding="{Binding EmployeeNumber}"  Width="50" />
                        <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}"  Width="80" />
                        <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="100" />
                        <GridViewColumn Header="Departments" DisplayMemberBinding="{Binding Department}" Width="80" />
                        <GridViewColumn Header="Titles" DisplayMemberBinding="{Binding Title}"  Width="80" />

                    </GridView>
                </ListView.View>

            </ListView>

            <!--<TextBox Grid.Row="1" Height="23"  HorizontalAlignment="Left" Margin="80,7,0,0" Name="txtUserId" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.UserId}" />-->
            <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,35,0,0" Name="txtFirstName" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.FirstName}" />
            <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,62,0,0" Name="txtLastName" VerticalAlignment="Top" Width="178" Text="{Binding ElementName=UserGrid,Path=SelectedItem.LastName}" />

            <!--<Label Content="UserId" Grid.Row="1" Height="28"  Margin="12,12,0,0" Name="label1"  VerticalAlignment="Top"/>-->
            <Label Content="Last Name" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,60,0,0" Name="label2" VerticalAlignment="Top" />
            <Label Content="First Name" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,35,0,0" Name="label3" VerticalAlignment="Top" />
            
            
            <!--update buto added button click-->

            <Button Content="Update" Grid.Row="1" Height="23"  HorizontalAlignment="Left" Margin="310,40,0,0" Name="btnUpdate" 
                 VerticalAlignment="Top" Width="141"
                Command="{Binding Path=UpdateCommand}"  />


            <!--<Button Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="141" "310,40,0,0" Content="Update" Click="Button_Click" Command="{Binding UpdateCommand}"/-->
<!--Binding ElementName - This is a markup extension which will tell XAML compiler to bind your ListView to Textbox control-->
            <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,117,0,0" x:Name="txtCity" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.Department, ElementName=UserGrid}" />
            <Label Content="Department" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,115,0,0" x:Name="label2_Copy" VerticalAlignment="Top" />

            <TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,88,0,0" x:Name="txtCountry" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.Title, ElementName=UserGrid}" />
            <Label Content="Title" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,86,0,0" x:Name="label2_Copy1" VerticalAlignment="Top" />

            <!--<TextBox Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="80,115,0,0" x:Name="txtSTate" VerticalAlignment="Top" Width="178" Text="{Binding SelectedItem.State, ElementName=UserGrid}" />
            <Label Content="" Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="12,113,0,0" x:Name="label2_Copy2" VerticalAlignment="Top" />-->

        </Grid>
    </Grid>
</Window>





我的模特是:



my model is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace Dataapplication.Model//model
{             //Model is responsible for exposing data
    //model should implement thje INotifyPropertyChanged and/or INotifyCollectionChanged .this is because 
    //if you are crating a property which needed to update the UI when the value of it is modified, the minimum requirement is to implement the same from INotifyPropertyChanged
    //similarly need to implement INotifyCollectionChanged when new item in to collection is to be reflected in UI(view) for example yo are using the listBox, and on click of button
    //if we nned to add some daata in to the listbox the UI will know through the INotifyCollectionChanged interface.

    public class Employee : INotifyPropertyChanged
    {
        int _employeeNumber;
        string _firstName;
        string _lastName;
        string _department;
        string _title;
        private Employee selectedEmployee;


        public Employee()
        {
            _employeeNumber = 0;
            _firstName =
            _lastName =
            _department =
            _title = null;
        }

        public int EmployeeNumber
        {
            get { return _employeeNumber; }
            set
            {
                _employeeNumber = value;
                OnPropertyChanged("EmployeeNumber");
            }
        }

        public string FirstName
        {
            get { return _firstName; }
            set
            {
                _firstName = value;
                OnPropertyChanged("FirstName");
            }
        }

        public string LastName
        {
            get { return _lastName; }
            set
            {
                _lastName = value;
                OnPropertyChanged("LastName");
            }
        }

        public string Department
        {
            get { return _department; }
            set
            {
                _department = value;
                OnPropertyChanged("Department");
            }
        }

        public string Title
        {
            get { return _title; }
            set
            {
                _title = value;
                OnPropertyChanged("Title");
            }
        }

        public Employee SelectedEmployee
        {
            get { return selectedEmployee; }
            set
            {
                selectedEmployee = value;
                OnPropertyChanged("SelectedEmployee");
            }
        }


        public override string ToString()
        {
            return String.Format("{0} {1} ({2})", FirstName, LastName, EmployeeNumber);
        }

        #region INotifyPropertyChanged Members
        //this is to verify that the property with a given name actually exists on the ViewModel object
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChangedEventArgs args = new PropertyChangedEventArgs(propertyName);//same as PropertyChanged(this, new  PropertyChangedEventArgs(propertyName));


                this.PropertyChanged(this, args);
            }
        }

        #endregion



    }


}

推荐答案

这篇关于UI未使用更新进行更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆