Silverlight:如何将通用列表数据绑定到组合框?
请原谅,我是新来的Silverlight,我仍然试图围绕数据绑定...Silverlight:如何将通用列表数据绑定到组合框?
我有一个使用LINQ从类获得的通用列表。该列表包含4个对象,每个对象由Letter属性(字符串 - A,B,C和D)以及相应的Number属性(整数-1,2,3和4)组成。
在Silverlight中,我有一个组合框控件和一个文本块。我想弄清楚如何:
- 绑定组合框的通用列表中,这样的字母填充组合框
- 当用户在组合框中选择一个字母(比如C),相应的整值(在本例中为3)显示在文本块中。
我一直在努力使它与ItemsSource一起工作,但没有得到任何地方。有什么建议?我在VB中工作,顺便......
感谢
我做了一个标签和一个radcombobox控件(Telerik的距离)类似的东西。
如果你想通过代码来做到这一点,你必须做这样的:
'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)
...如果你想直接在XAML做到这一点,看看at this后对于第2步
我只会在XAML中执行此操作。这里是我的(样本)代码:
<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>
这里是我的背后代码:(编辑:SRY的C#代码)
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();
}
}
记住:这仅仅是一个示例代码。我强烈建议你看看MVVM(http://jesseliberty.com/2010/05/08/mvvm-its-not-kool-aid-3/)。更好的解决方案是,将SelectedItem(或选定的值)绑定到ViewModel,然后在TextBlock中引用此值。
BR,
TJ
感谢MVVM链接。我一直在试图围绕这一点,并且页面看起来非常有帮助。 – mraviator 2011-01-21 12:41:36
大纲工作出色,非常感谢! – mraviator 2011-01-21 12:46:56