2011-01-21 117 views
0

請原諒,我是新來的Silverlight,我仍然試圖圍繞數據綁定...Silverlight:如何將通用列表數據綁定到組合框?

我有一個使用LINQ從類獲得的通用列表。該列表包含4個對象,每個對象由Letter屬性(字符串 - A,B,C和D)以及相應的Number屬性(整數-1,2,3和4)組成。

在Silverlight中,我有一個組合框控件和一個文本塊。我想弄清楚如何:

  1. 綁定組合框的通用列表中,這樣的字母填充組合框
  2. 當用戶在組合框中選擇一個字母(比如C),相應的整值(在本例中爲3)顯示在文本塊中。

我一直在努力使它與ItemsSource一起工作,但沒有得到任何地方。有什麼建議?我在VB中工作,順便......

感謝

回答

0

我做了一個標籤和一個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步

+0

大綱工作出色,非常感謝! – mraviator 2011-01-21 12:46:56

0

我只會在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

+0

感謝MVVM鏈接。我一直在試圖圍繞這一點,並且頁面看起來非常有幫助。 – mraviator 2011-01-21 12:41:36