繁体   English   中英

来自 GridView 控件的 UWP 组合框 SelectedItem 以及使用 MVVM 模式将选择更改值绑定到模型

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

我在尝试着

  1. 当用户在数据网格行上选择时选择组合框项
  2. 当用户添加新用户时,用户从我的视图模型中的组合框中选择的项目,我尝试过的是:查看:

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

我的文本框和组合框如下所示:

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

模型 :

 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

    }

查看型号:

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");
            }
        }


    }

我已经为文本框控件完成了这个工作,但对于组合框我找不到我想要做的,所以请帮助我

但是当尝试在组合框中做同样的事情并且它不起作用时,我的组合框没有任何项目源,它只有静态项目列表。

问题是您为ComboBox绑定了错误的属性(文本属性)。 对于您的场景,您需要为ComboBox制作一个国家/地区列表并绑定SelectedItem属性。 我已经重写了你的代码。 请检查以下内容。

用户.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

}

用户模型.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 代码

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

这是您可以参考的完整代码项目

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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