WPF: How to bind object to ComboBox

后端 未结 3 1376
清歌不尽
清歌不尽 2020-12-13 02:13

Trying to learn how to bind objects to various types of controls. In this instance, I want to get sample data in my object to appear in ComboBox. The code runs but what appe

相关标签:
3条回答
  • 2020-12-13 02:34

    Trying to get selected value from combobox returns System.Data.Entity.DynamicProxies.x

     private void Button_Click(object sender, RoutedEventArgs e){
             string _scanner0 = int.Parse(mycmb.SelectedValue.ToString());
             string _scanner1 = mycbr.SelectedItem.ToString();
             string _scanner2 = mycbr.SelectedValuePath.ToString();
             string _scanner3 = mycbr.text.ToString();
         }
    

    all these Returns System.Data.Entity.DynamicProxies.x What should i do?

    0 讨论(0)
  • 2020-12-13 02:54

    There are several ways to tell the framework what to display

    1) Use DisplayMemberPath on the ComboBox (this will display the named property):

    <ComboBox ItemsSource="{Binding Path=Clients}" 
              DisplayMemberPath="Name"
    />
    

    2) Set ItemTemplate on the ComboBox. This is like #1, except allows you to define a template to display, rather than just a property:

    <ComboBox ItemsSource="{Binding Path=Clients}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <Border BorderBrush="Green" BorderThickness="1" Padding="5">
                    <TextBlock Text="{Binding Path=Name,StringFormat='Name: {0}'}" />
                </Border>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
    

    3) Add a ToString() override to source class. Useful if you always want to display the same string for a given class. (Note that the default ToString() is just the class type name, which is why you see "TheProtect.UserControls.Client".)

    public class Client
    {
        // ...
    
        public override string ToString()
        {
            return string.Format("{0} ({1})", Name, ID);
        }
    }
    

    4) Add a DataTemplate to the XAML resources. This is useful for associating a given class type with a more complex or stylized template.

    <UserControl xmlns:local="clr-namespace:TheProject.UserControls">
        <UserControl.Resources>
            <DataTemplate DataType="local:Client">
                <TextBlock Text="{Binding Name}" />
            </DataTemplate>
        </UserControl.Resources>
    
        // ...
    
    </UserControl>    
    
    0 讨论(0)
  • 2020-12-13 02:56

    In DisplayMemberPath, give the name of the property which you want to show in the comboBox. In SelectedValuePath, give the name of the property which you want to select. When you do a ComboBox.SelectedValue, you will get the value of this property.

    0 讨论(0)
提交回复
热议问题