Silverlight: How do I bind generic list data to combobox?
Please forgive, I'm new to Silverlight and am still trying to wrap my head around data binding...
I have a generic list obtained from a class using LINQ. The list has 4 objects, each object consisting of a Letter property (string - A, B, C and D) and a corresponding Number property (integer - 1, 2, 3, and 4).
In Silverlight, I have a combobox control and a text block. I'm trying to figure out how to:
- Bind the combobox to the generic list so that the letters populate the combobox
- When the user 开发者_如何学编程selects a letter in the combobox (say C), the corresponding integer value (3 for this example) is displayed in the text block.
I'm been trying to make it work with ItemsSource, but am not getting anywhere. Any advice? I'm working in VB, by the way...
Thanks
I did something similar with a Label and a radComboBox (from Telerik).
If you want to do this by code, you'll have to do it like this:
'This code is untested but at least it shows the logic
'Step #1, filling the combobox
yourComboBox.ItemsSource = yourList
yourComboBox.SelectedValuePath = "IntegerPropertyName"
yourComboBox.DisplayMemberPath = "StringPropertyName"
'Step #2, binding the TextBlock
Dim binding As System.Windows.Data.Binding = Nothing
binding = New System.Windows.Data.Binding()
binding.Source = yourComboBox
binding.Mode = Data.BindingMode.TwoWay 'Maybe in your case you'll want OneWay
binding.Path = New System.Windows.PropertyPath("SelectedItem.IntegerPropertyName")
youtTextBlock.SetBinding(TextBlock.TextProperty, binding)
... and if you want to do it directly in the XAML, have a look at this post for step #2
I would do this in XAML only. Here is my (Sample) Code:
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock Text="{Binding ElementName=MyComboBox, Path=SelectedValue}" VerticalAlignment="Top"/>
<ComboBox
x:Name="MyComboBox"
ItemsSource="{Binding MyColl}"
Height="22"
SelectedValuePath="I"
DisplayMemberPath="C"/>
</Grid>
And here is my Code behind: (EDIT: sry for the c# code)
public class MyClass
{
public int I { get; set; }
public string C { get; set; }
}
public partial class MainPage : UserControl
{
public ObservableCollection<MyClass> MyColl { get; set; }
public MainPage()
{
MyColl = new ObservableCollection<MyClass>();
MyColl.Add(new MyClass{ C = "A", I = 1});
MyColl.Add(new MyClass { C = "B", I = 2 });
MyColl.Add(new MyClass { C = "C", I = 3 });
MyColl.Add(new MyClass { C = "D", I = 4 });
DataContext = this;
InitializeComponent();
}
}
Remember: This is just a sample code. I strongly recommend you to hav a look at MVVM (http://jesseliberty.com/2010/05/08/mvvm-its-not-kool-aid-3/). A better Solution would be, to bind the SelectedItem (or the selected value) to your ViewModel, and then reference this value in the TextBlock.
BR,
TJ
精彩评论