I have created a combo box with data binding in WP

2020-04-27 07:51发布

This my Xaml code for combo box with data binding :

        <ComboBox Name="C1"  ItemsSource="{Binding}" HorizontalAlignment="Left" Margin="126,127,0,0" VerticalAlignment="Top" Width="218" SelectionChanged="C1_SelectionChanged" >
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Margin="2"  Text="{Binding CUS_DESCRIPTION}" />
            </DataTemplate>
        </ComboBox.ItemTemplate>
        <ComboBox.ItemContainerStyle>
            <Style TargetType="{x:Type ComboBoxItem}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate>
                            <Grid x:Name="gd"  TextElement.Foreground="Black">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition/>
                                    <ColumnDefinition/>
                                    <ColumnDefinition/>
                                </Grid.ColumnDefinitions>
                                <TextBlock Margin="5" Grid.Column="0" Text="{Binding CUSTOMER_NAME}"/>
                                <TextBlock Margin="5" Grid.Column="1" Text="{Binding CUS_DESCRIPTION}"/>
                            </Grid>
                            <ControlTemplate.Triggers>
                                <Trigger Property="ComboBoxItem.IsSelected" Value="True">
                                    <Setter TargetName="gd"  Property="Background" Value="Gray"></Setter>
                                    <Setter TargetName="gd"  Property="TextElement.Foreground" Value="White"></Setter>
                                </Trigger>
                                <Trigger Property="ComboBoxItem.IsMouseOver" Value="True">
                                    <Setter TargetName="gd"  Property="Background" Value="Blue"></Setter>
                                    <Setter TargetName="gd"  Property="TextElement.Foreground" Value="White"></Setter>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ComboBox.ItemContainerStyle>
    </ComboBox>

I have created a combo box with data binding in WPF application. Combo box items are add by using Observable Collection object.I am not sure how to get value and set value of "comboboxselecteditem". I used "combobox.selecteditem.tostring();" to get value, but it shows "windows name + object name that used in loading combo box". similarly I am not able to set a value to combo box as a default value.I need like when window opens the combo box "selectedboxitem" should hold the value that I set.

This my c# code:

public partial class MainWindow : Window
{
   private ObservableCollection<CUSTOMER> CUSTOMERS=new ObservableCollection<CUSTOMER> ();
    public MainWindow()
    {
        InitializeComponent();
        c2.Items.Add("hi");

        OleDbConnection connect = new OleDbConnection();
        connect.ConnectionString = @"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\mani\Documents\RAVI.mdb";

        try
        {
            OleDbCommand cmd = new OleDbCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "Select * from RICE_CUSTOMER";


            cmd.Connection = connect;
            connect.Open();
            cmd.ExecuteNonQuery();
            OleDbDataReader R1 = cmd.ExecuteReader();
            if (R1.HasRows)
            {
                while (R1.Read())
                {
                    CUSTOMERS.Add(new CUSTOMER() { CUSTOMER_NAME = R1[0].ToString(), CUS_DESCRIPTION = R1[3].ToString() });
                }
                DataContext = CUSTOMERS;
            }

                     connect.Close();              
        }

        catch (OleDbException ex)
        {
            MessageBox.Show(ex.ToString());

        }

    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {         
            Window1 W = new Window1();
            W.Show();
            this.Hide();
    }


    class CUSTOMER
    {
        public string CUSTOMER_NAME{get;set;}
        public string CUS_DESCRIPTION{get;set;}
    }

    private void C1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
       string c=C1.selecteditem.tostring();
       Messagebox.show(c); 
       C1.selecteditem=value;    
    }
}

}

标签: c# wpf xaml
2条回答
小情绪 Triste *
2楼-- · 2020-04-27 08:05

You can get and set the ComboBox's SelectedItem by binding to it, just as you bound the items of the ComboBox.

It is a good practice to put the data members for your UI into a separate class. This is typically done in a view model using the MVVM (Model, View, View Model) paradigm.

Something like this:

class ViewModel : INotifyPropertyChanged
{
    private ObservableCollection<CUSTOMER> _customers = new ObservableCollection<CUSTOMER>();
    public IList<CUSTOMER> Customers
    {
        get { return _customers; }
    }

    private CUSTOMER _selectedCustomer = null;
    public CUSTOMER SelectedCustomer
    {
        get { return _selectedCustomer; }
        set
        {
            _selectedCustomer = value;
            OnPropertyChanged("SelectedCustomer");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propName)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propName));
    }
}

And in your window class:

class MainWindow
{
    public MainWindow()
    {
        InitializeComponent();

        DataContext = new ViewModel();
    }
}

And finally in your XAML:

<ComboBox ItemsSource="{Binding Path=Customers}"
          SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}">
    ...
</ComboBox>

I would also move the code that loads the customers from the database into the ViewModel, and once done set the SelectedCustomer property to a reasonable default. For example, to select the customer whose name is Bob, run the following once the objects have been loaded from the database:

SelectedCustomer = _customers.FirstOrDefault(customer => customer.CUSTOMER_NAME.Equals("Bob"));
查看更多
唯我独甜
3楼-- · 2020-04-27 08:10

You could cast the SelectedItem property of the ComboBox to a CUSTOMER object to get the currently selected item:

CUSTOMER selectedCustomer = C1.SelectedItem as CUSTOMER;
if(selectedCustomer != null)
    MessageBox.Show(selectedCustomer.CUSTOMER_NAME);

To select an item you set the SelectedItem property to a CUSTOMER object that is included in the ComboBox's ItemsSource:

C1.SelectedItem = C1.Items[0]; //selects the first customer (index = 0)

Or if you know the name or description of the customer:

string theName = "some customer name...";
C1.SelectedItem = C1.Items.OfType<CUSTOMER>().FirstOrDefault(x => x.CUSTOMER_NAME == theName);
查看更多
登录 后发表回答