[英]How to bind data with combobox
我需要以最簡單的方式知道如何在XAML中將數據(字符串列表)綁定到ComboBox而不在后面的代碼中使用ComboBox.ItemSource = object 。
我的意思是什么:
{Binding Path="What Comes here"}
假設我有:
class Window1 : UserControl {
List<String> list = new List<String>();// And assign Value to this list
...}
我試過了
{Binding Path=list} or {Binding list}
但沒有任何約束。 那么應該怎么做呢? (我無法在后面的代碼中訪問此組合框,因為Microsoft將SilverLight DatGrid限制為我無法做到的程度 )
綁定規則很少能正常工作:
回到您需要綁定到在后面的代碼中創建的列表的問題陳述中,您必須對代碼進行以下更改:
// Not sure why you termed it as Window1 if it's actually an UserControl.
public partial class Window1 : UserControl
{
public Window1()
{
InitializeComponent();
MyStrings = new List<string>(new[] { "A", "B", "C", "D" });
DataContext = this; // Rule #2
}
public List<string> MyStrings { get; set; } // Rule #1
}
XAML :
<ComboBox ItemsSource="{Binding MyStrings}"/>
如果您未在UserControl的構造函數中設置DataContext並仍要綁定到屬性,請使用RelativeSource綁定(規則3)
<ComboBox ItemsSource="{Binding MyStrings, RelativeSource={RelativeSource FindAncestor
, AncestorType=UserControl}}"/>
附加點
ObservableCollection<string>
代替List<string>
。 在這里看看: Model-View-ViewModel(MVVM)解釋了
我不是SilverLight開發人員,但據我所知,它只是完整wpf的降級版本。
嘗試使用ViewModel並在其中定義列表。 然后,您可以將ComboBox.ItemsSource
屬性綁定到它:
public class SomeViewModel : INotifyPropertyChanged
{
private ObservableCollection<string> listOfAwesomeStrings;
public ObservableCollection<string> ListOfAwesomeStrings
{
get { return listOfAwesomeStrings; }
set
{
if (value.Equals(listOfAwesomeStrings))
{
return;
}
listOfAwesomeStrings= value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
像這樣設置視圖的DataContext
並填充您的列表:
var viewModel = new SomeViewModel();
viewModel.ListOfAwesomeStrings = new ObservableCollection<string>();
viewModel.ListOfAwesomeStrings.Add("Option 1");
viewModel.ListOfAwesomeStrings.Add("Option 2");
viewModel.ListOfAwesomeStrings.Add("Option 3");
this.DataContext = viewModel;
最后綁定到您在xaml中的屬性:
<ComboBox ItemsSource="{Binding ListOfAwesomeStrings}" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.