简体   繁体   中英

UWP Combobox SelectedItem from GridView Control and also Bind selection change value to model with MVVM Pattern

i am trying to

  1. Select Combobox Item when user select on datagrid row
  2. when user add new user then item selected by user from combobox in my view model and what i have tried is follow : View:

        <Button Content="Update" Grid.Row="12" Height="35" Grid.Column="0" Margin="90,15,0,0" Name="btnUpdate"   
                VerticalAlignment="Top" Width="141"  
                Command="{Binding Path=UpdateCommand}" 
                CommandParameter="{Binding Path=_Userdetails}"
                >

        </Button>
        <controls:DataGrid x:Name="dgvEmpList" Margin="0,0,480,457"
                           Grid.Row="1" Grid.RowSpan="12" Grid.Column="1" GridLinesVisibility="All"
                           AlternatingRowBackground="LightBlue"
                           HeadersVisibility="Column"
                           ItemsSource="{Binding Users, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"   
                          SelectedItem="{Binding SelectedUser, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                           AutoGenerateColumns="False"
                          >
            <controls:DataGrid.Columns>
                <controls:DataGridTextColumn 
            Header="UserId"            
            Binding="{Binding UserId}" 
             />
                <controls:DataGridTextColumn 
            Header="FirstName"            
            Binding="{Binding FirstName}" 
             />
                <controls:DataGridTextColumn 
            Header="LastName"            
            Binding="{Binding LastName}" 
             />

                <controls:DataGridTextColumn 
            Header="City"

            Binding="{Binding City}" />
                <controls:DataGridTextColumn 
            Header="State"

            Binding="{Binding State}" />
                <controls:DataGridTextColumn 
            Header="Country"

            Binding="{Binding Country}" />




            </controls:DataGrid.Columns>

        </controls:DataGrid>
</Grid>

My text box and Combobox are in view like :

<TextBlock x:Name="label2" Padding="18,0,0,0" Margin="10,20,0,0" Text="First Name :"  Grid.Row="2" Grid.Column="0" TextAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Left" Height="19" Width="86"/>
        <TextBox x:Name="txtFName" TextWrapping="Wrap" Text="{Binding _Userdetails.FirstName,Mode=TwoWay}" SelectedText="{Binding SelectedUser.FirstName}" AcceptsReturn="True"   PlaceholderText="Enter FirstName ..." Grid.Row="3" Grid.Column="0" Width="292" TextAlignment="Left" VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="28,0,0,0" Height="32"></TextBox>
 <ComboBox x:Name="cmbCountry" PlaceholderText="Select Country ..." Text="{Binding _Userdetails.Country,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Grid.Row="11" Grid.Column="0" Width="292"  VerticalAlignment="Center" HorizontalAlignment="Left" Margin="28,0,0,0" Height="32">
            <ComboBoxItem Content="India"></ComboBoxItem>
            <ComboBoxItem Content="Canada"></ComboBoxItem>
            <ComboBoxItem Content="USA"></ComboBoxItem>
            <ComboBoxItem Content="ENGLAND"></ComboBoxItem>
            <ComboBoxItem Content="New Zealand"></ComboBoxItem>
        </ComboBox>

Model :

 public class User : BindableBase
    {
        private int userId;
        private string firstName;
        private string lastName;
        private string city;
        private string state;
        private string country;
        public int UserId
        {
            get
            {
                return userId;
            }
            set
            {
                userId = value;
                OnPropertyChanged("UserId");
            }
        }
        public string FirstName
        {
            get
            {
                return firstName;
            }
            set
            {
                firstName = value;
                OnPropertyChanged("FirstName");
            }
        }
        public string LastName
        {
            get
            {
                return lastName;
            }
            set
            {
                lastName = value;
                OnPropertyChanged("LastName");
            }
        }
        public string City
        {
            get
            {
                return city;
            }
            set
            {
                city = value;
                OnPropertyChanged("City");
            }
        }
        public string State
        {
            get
            {
                return state;
            }
            set
            {
                state = value;
                OnPropertyChanged("State");
            }
        }
        public string Country
        {
            get
            {
                return country;
            }
            set
            {
                country = value;
                OnPropertyChanged("Country");
            }
        }

        #region INotifyPropertyChanged Members  

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

    }

View Model :

public class UserViewModel : User,INotifyPropertyChanged
    {

        private ObservableCollection<User> _UsersList { get; set; }
        private User selecteduser;
        public event PropertyChangedEventHandler PropertyChanged;
        public User _Userdetails { get; set; }
        protected void OnPropertyChanged(string propertyName)//string propertyName
        {
            if (PropertyChanged != null)

            {
                PropertyChangedEventArgs args = new PropertyChangedEventArgs(propertyName);
                this.PropertyChanged(this, args);
            }
        }

        public UserViewModel()
        {
            _UsersList = new ObservableCollection<User>
            {
                new User{UserId = 1,FirstName="Raj",LastName="Beniwal",City="Delhi",State="DEL",Country="INDIA"},
                new User{UserId=2,FirstName="Mark",LastName="henry",City="New York", State="NY", Country="USA"},
                new User{UserId=3,FirstName="Mahesh",LastName="Chand",City="Philadelphia", State="PHL", Country="USA"},
                new User{UserId=4,FirstName="Vikash",LastName="Nanda",City="Noida", State="UP", Country="CANADA"},
                new User{UserId=5,FirstName="Harsh",LastName="Kumar",City="Ghaziabad", State="UP", Country="INDIA"},
                new User{UserId=6,FirstName="Reetesh",LastName="Tomar",City="Mumbai", State="MP", Country="INDIA"},
                new User{UserId=7,FirstName="Deven",LastName="Verma",City="Palwal", State="HP", Country="ENGLAND"},
                new User{UserId=8,FirstName="Ravi",LastName="Taneja",City="Delhi", State="DEL", Country="INDIA"}
            };
            try
            {
                _Userdetails = new User();

            }
            catch 
            {
            }
            UpdateCommand = new RelayCommand(AddUserMethod);


        }
        public RelayCommand UpdateCommand { get; set; }


        public void AddUserMethod(object parameter)
        {
            try
            {
                _UsersList.Add(
                new User
                {

                    FirstName = _Userdetails.FirstName,
                    LastName = _Userdetails.LastName,
                    City = _Userdetails.City,
                    Country = _Userdetails.Country,
                    State = _Userdetails.State,
                    UserId = _Userdetails.UserId

                });
            }
            catch
            {

            }




        }
        public User userdetails
        {
            get
            {
                return _Userdetails;
            }
            set
            {
                _Userdetails = value;
                OnPropertyChanged("userdetails");
            }
        }

        public User SelectedUser
        {
            get
            {
                return selecteduser;
            }
            set
            {
                selecteduser = value;
                OnPropertyChanged("SelectedUser");
            }
        }

        public ObservableCollection<User> Users
        {
            get
            { return _UsersList; }
            set
            {
                _UsersList = value;
                OnPropertyChanged("Users");
            }
        }


    }

i have done this for textbox controls which works fine but for combobox i can't find what i want to do so please help me

but when try to do same in combobox and it doesnot work my combobox doesn't have any itemsource itjust have static items list.

The problem is you have bind wrong property (Text Property ) for ComboBox . For your scenario, you need to make a country list for ComboBox and bind SelectedItem property. I have re-write your code. please check the following.

User.cs

public class User : ViewModelBase
{
    private int userId;
    private string firstName;
    private string lastName;
    private string city;
    private string state;
    private string country;
    public int UserId
    {
        get
        {
            return userId;
        }
        set
        {
            userId = value;
            OnPropertyChanged("UserId");
        }
    }
    public string FirstName
    {
        get
        {
            return firstName;
        }
        set
        {
            firstName = value;
            OnPropertyChanged("FirstName");
        }
    }
    public string LastName
    {
        get
        {
            return lastName;
        }
        set
        {
            lastName = value;
            OnPropertyChanged("LastName");
        }
    }
    public string City
    {
        get
        {
            return city;
        }
        set
        {
            city = value;
            OnPropertyChanged("City");
        }
    }
    public string State
    {
        get
        {
            return state;
        }
        set
        {
            state = value;
            OnPropertyChanged("State");
        }
    }
    public string Country
    {
        get
        {
            return country;
        }
        set
        {
            country = value;
            OnPropertyChanged("Country");
        }
    }

    #region INotifyPropertyChanged Members  

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion

}

UserModel.cs

public class UserViewModel : User, INotifyPropertyChanged
{

    private ObservableCollection<User> _usersList;
    private User _userdetails;
    private User _selecteduser;
    private string _countrySelectItem;
    public ObservableCollection<string> CountryList { get; set; }
    public User Userdetails
    {
        get
        {
            return _userdetails;
        }
        set
        {
            _userdetails = value;
            OnPropertyChanged("Userdetails");
        }
    }

    public string CountrySelectItem
    {
        get
        {
            return _countrySelectItem;
        }
        set
        {
            _countrySelectItem = value;
            _userdetails.Country = _countrySelectItem;
            OnPropertyChanged("CountrySelectItem");
        }
    }

    public User SelectedUser
    {
        get
        {
            return _selecteduser;
        }
        set
        {
            _selecteduser = value;

           if( CountryList.Any(p => p == _selecteduser.Country))
            {
                CountrySelectItem = _selecteduser.Country;
            }else
            {
                CountrySelectItem = null;
            }

            OnPropertyChanged("SelectedUser");
        }
    }

    public ObservableCollection<User> Users
    {
        get
        { return _usersList; }
        set
        {
            _usersList = value;
            OnPropertyChanged("Users");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)//string propertyName
    {
        if (PropertyChanged != null)

        {
            PropertyChangedEventArgs args = new PropertyChangedEventArgs(propertyName);
            this.PropertyChanged(this, args);
        }
    }

    public UserViewModel()
    {
        _usersList = new ObservableCollection<User>
        {
            new User{UserId=1,FirstName="Raj",LastName="Beniwal",City="Delhi",State="DEL",Country="INDIA"},
            new User{UserId=2,FirstName="Mark",LastName="henry",City="New York", State="NY", Country="USA"},
            new User{UserId=3,FirstName="Mahesh",LastName="Chand",City="Philadelphia", State="PHL", Country="USA"},
            new User{UserId=4,FirstName="Vikash",LastName="Nanda",City="Noida", State="UP", Country="CANADA"},
            new User{UserId=5,FirstName="Harsh",LastName="Kumar",City="Ghaziabad", State="UP", Country="INDIA"},
            new User{UserId=6,FirstName="Reetesh",LastName="Tomar",City="Mumbai", State="MP", Country="INDIA"},
            new User{UserId=7,FirstName="Deven",LastName="Verma",City="Palwal", State="HP", Country="ENGLAND"},
            new User{UserId=8,FirstName="Ravi",LastName="Taneja",City="Delhi", State="DEL", Country="INDIA"},
             new User{UserId=9,FirstName="Nico",LastName="Ming",City="WuXi", State="DEL", Country="China"}
        };
        CountryList = new ObservableCollection<string>()
        {
            "INDIA",
            "CANADA",
            "USA",
            "ENGLAND",
            "New Zealand"
        };

        try
        {
            _userdetails = new User();

        }
        catch
        {
        }

        UpdateCommand = new RelayCommand<User>(AddUserMethod);
    }
    public RelayCommand<User> UpdateCommand { get; set; }

    public void AddUserMethod(User parameter)
    {
        try
        {
            _usersList.Add(
            new User
            {

                FirstName = _userdetails.FirstName,
                LastName = _userdetails.LastName,
                City = _userdetails.City,
                Country = _userdetails.Country,
                State = _userdetails.State,
                UserId = _userdetails.UserId

            });
        }
        catch
        {

        }
    }
}

Xaml code

<Page.DataContext>
    <local:UserViewModel x:Name="ViewModel" />
</Page.DataContext>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="6*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Button
        Name="btnUpdate"
        Grid.Row="0"
        Width="141"
        Height="35"
        Margin="90,15,0,0"
        VerticalAlignment="Top"
        Command="{Binding Path=UpdateCommand}"
        CommandParameter="{Binding Path=Userdetails}"
        Content="Update"
        />

    <controls:DataGrid
        x:Name="dgvEmpList"
        Grid.Row="1"
        AlternatingRowBackground="LightBlue"
        AutoGenerateColumns="False"
        GridLinesVisibility="All"
        HeadersVisibility="Column"
        ItemsSource="{Binding Users, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
        SelectedItem="{Binding SelectedUser, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
        >
        <controls:DataGrid.Columns>
            <controls:DataGridTextColumn Binding="{Binding UserId}" Header="UserId" />
            <controls:DataGridTextColumn Binding="{Binding FirstName}" Header="FirstName" />
            <controls:DataGridTextColumn Binding="{Binding LastName}" Header="LastName" />
            <controls:DataGridTextColumn Binding="{Binding City}" Header="City" />
            <controls:DataGridTextColumn Binding="{Binding State}" Header="State" />
            <controls:DataGridTextColumn Binding="{Binding Country}" Header="Country" />
        </controls:DataGrid.Columns>
    </controls:DataGrid>

    <TextBox
        x:Name="txtFName"
        Grid.Row="2"
        Grid.RowSpan="2"
        Width="292"
        Height="32"
        Margin="28,0,0,0"
        HorizontalAlignment="Left"
        VerticalAlignment="Bottom"
        AcceptsReturn="True"
        PlaceholderText="Enter FirstName ..."
        SelectedText="{Binding SelectedUser.FirstName}"
        Text="{Binding Userdetails.FirstName, Mode=TwoWay}"
        TextAlignment="Left"
        TextWrapping="Wrap"
        />
    <ComboBox
        x:Name="cmbCountry"
        Grid.Row="4"
        Width="292"
        Height="32"
        Margin="28,0,0,0"
        HorizontalAlignment="Left"
        VerticalAlignment="Center"
        ItemsSource="{Binding CountryList}"
        PlaceholderText="Select Country ..."
        SelectedItem="{Binding CountrySelectItem,Mode=TwoWay}"   
        >

        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding}"/>
            </DataTemplate>
        </ComboBox.ItemTemplate>

    </ComboBox>
</Grid>

And this is complete code project that you could refer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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