Progolfer79
Progolfer79

Reputation: 87

WPF MVVM Combobox SelectionChanged/SelectedItem

I am building a WPF App using MVVM and a mySql database. I am having a difficult time getting the SelectedItem from a ComboBox stored in a Property. Basically, at this point, I would like the SelectedItem displayed in a Textbox. That will help me understand the Binding process better, as I'm still learning.

Ultimately, I would like to use the stored value/property as a reference for pulling another value from the DB. Below is some sample code. Any help would be greatly appreciated. Thank you!

VIEW

        <Grid Background="AliceBlue">

        <Label Content="Street Address" HorizontalAlignment="Left" Margin="10,54,0,0" VerticalAlignment="Top" Width="87" Height="28"/>
        <Label Content="State" HorizontalAlignment="Left" Margin="10,125,0,0" VerticalAlignment="Top" Width="87" Height="22"/>


        <TextBox Name="txtStreetAddress" HorizontalAlignment="Left" Height="23" Margin="119,55,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"
                 Text="{Binding StreetAddress, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                 />
        <ComboBox Name="cboState" 
              HorizontalAlignment="Left" Margin="119,125,0,0" VerticalAlignment="Top" Width="52"
              DisplayMemberPath="StateAbb"
              ItemsSource="{Binding StateAbbList}"
              SelectedItem="{Binding SelectedStateAbb, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
              />

        <TextBox HorizontalAlignment="Left" Height="23" Margin="180,124,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="59"
                 Text="{Binding SelectedStateAbb, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                 />


    </Grid>

VIEW MODEL

public class AddStreetAddressVM : ObservableObject, IPageViewModel
{

    public string Name
    {
        get
        {
            return "Add Street Address";
        }
    }

    const string dbConnectionString = @"datasource=localhost;port=3306;Initial Catalog='optest1a1';username=root;password=";

    private ICommand _cboStateAbb;

    private string _streetAddress;
    private ObservableCollection<tblStateAbb> _stateAbbList;
    private string _selectedStateAbb;
    private int _selectedStateNum;

    public ICommand CboStateAbb
    {
        get
        {
            if (_cboStateAbb == null)
            {
                _cboStateAbb = new RelayCommand(param => this.fillStateAbb(), null);
            }

            return _cboStateAbb;
        }
    }

    public string StreetAddress
    {
        get { return _streetAddress; }
        set { SetProperty(ref _streetAddress, value, () => StreetAddress); }
    }

    public ObservableCollection<tblStateAbb> StateAbbList
    {
        get { return _stateAbbList; }
        set
        {
            SetProperty(ref _stateAbbList, value, () => StateAbbList);
        }
    }

    public string SelectedStateAbb
    {
        get { return _selectedStateAbb; }
        set
        {
            SetProperty(ref _selectedStateAbb, value, () => SelectedStateAbb);
            //if (_selectedStateAbb != null)
            //{
            //    GetStateNum();
            //}

            //_selectedStateAbb = value;
        }
    }

    public int SelectedStateNum
    {
        get { return _selectedStateNum; }
        set { SetProperty(ref _selectedStateNum, value, () => SelectedStateNum); }
    }

    public AddStreetAddressVM() : base()
    {
        StateAbbList = new ObservableCollection<tblStateAbb>();
        fillStateAbb();
    }

    private void fillStateAbb()
    {
        using (MySqlConnection con = new MySqlConnection(dbConnectionString))
        {
            StateAbbList = new ObservableCollection<tblStateAbb>();
            con.Open();
            string Query = "SELECT * FROM tbl_states";
            MySqlCommand createCommand = new MySqlCommand(Query, con);
            MySqlDataReader dr = createCommand.ExecuteReader();
            int count = 1;
            while (dr.Read())
            {
                string StateAbb = dr.GetString(2);
                tblStateAbb stateabb = new tblStateAbb(count, StateAbb);
                StateAbbList.Add(stateabb);
                count++;
            }
            con.Close();
        }
    }

    private void GetStateNum()
    {
        using (MySqlConnection con = new MySqlConnection(dbConnectionString))
        {
            con.Open();
            string Query = "SELECT State_Num FROM tbl_states WHERE State_Abb='" + SelectedStateAbb + "' ";
            MySqlCommand createCommand = new MySqlCommand(Query, con);
            MySqlDataReader dr = createCommand.ExecuteReader();
            int count = 1;
            while (dr.Read())
            {
                int StateNum = dr.GetInt32(1);
                StateNum = SelectedStateNum;
            }
            con.Close();
        }

    }

}

MODEL - State Abbreviations

public class tblStateAbb : ObservableObject
{
    private Int32 _count;
    private String _stateAbb;
    private Int32 _stateNum;
    private ObservableCollection<tblStateAbb> _tblStateAbb;

    public Int32 Count
    {
        get { return _count; }
        set { SetProperty(ref _count, value, () => Count); }
    }

    public String StateAbb
    {
        get { return _stateAbb; }
        set { SetProperty(ref _stateAbb, value, () => StateAbb); }
    }

    public Int32 StateNum
    {
        get { return _stateNum; }
        set { SetProperty(ref _stateNum, value, () => StateNum); }
    }

    public ObservableCollection<tblStateAbb> StateAbbList
    {
        get { return _tblStateAbb; }
        set { SetProperty(ref _tblStateAbb, value, () => StateAbbList); }
    }

    public tblStateAbb() : base()
    {
        Count = 0;
        StateAbb = "";
        StateAbbList = new ObservableCollection<tblStateAbb>();
    }

    public tblStateAbb(int count, string stateabb) : base()
    {
        Count = count;
        StateAbb = stateabb;
        StateAbbList = new ObservableCollection<tblStateAbb>();
    }

    public tblStateAbb(int count, string stateabb, int statenum) : base()
    {
        Count = count;
        StateAbb = stateabb;
        StateNum = statenum;
        StateAbbList = new ObservableCollection<tblStateAbb>();
    }

}

OBSERVABLE OBJECT (INotifyPropertyChange)

public abstract class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propName)
    {
        Debug.Assert(GetType().GetProperty(propName) != null);

        var pc = PropertyChanged;
        if (pc != null)
        {
            pc(this, new PropertyChangedEventArgs(propName));
        }
    }

    protected bool SetProperty<T>(ref T field, T value, string propName)
    {
        if (!EqualityComparer<T>.Default.Equals(field, value))
        {
            field = value;
            OnPropertyChanged(propName);
            return true;
        }

        return false;
    }

    protected bool SetProperty<T>(ref T field, T value, Expression<Func<T>> expr)
    {
        if (!EqualityComparer<T>.Default.Equals(field, value))
        {
            field = value;
            var lambda = (LambdaExpression)expr;
            MemberExpression memberExpr;

            if (lambda.Body is UnaryExpression)
            {
                var unaryExpr = (UnaryExpression)lambda.Body;
                memberExpr = (MemberExpression)unaryExpr.Operand;
            }
            else
            {
                memberExpr = (MemberExpression)lambda.Body;
            }

            OnPropertyChanged(memberExpr.Member.Name);
            return true;
        }

        return false;
    }
}

RELAY COMMAND

    public class RelayCommand : ICommand
{
    private Action<object> execute;
    private Func<object, bool> canExecute;

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
    {
        this.execute = execute;
        this.canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        return this.canExecute == null || this.canExecute(parameter);
    }

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

Upvotes: 0

Views: 3621

Answers (1)

mm8
mm8

Reputation: 169200

Since SelectedStateAbb is a string, you should set the SelectedValuePath property of the ComboBox to "StateAbb" and bind the SelectedValue property to SelectedStateAbb:

<ComboBox Name="cboState" 
        HorizontalAlignment="Left" Margin="119,125,0,0" VerticalAlignment="Top" Width="52"
        DisplayMemberPath="StateAbb"
        SelectedValuePath="StateAbb"
        ItemsSource="{Binding StateAbbList}"
        SelectedValue="{Binding SelectedStateAbb, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

<TextBox HorizontalAlignment="Left" Height="23" Margin="180,124,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="59"
         Text="{Binding SelectedStateAbb, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

Upvotes: 2

Related Questions