[英]WPF: comboBox data binding issue
我有一個public class LPosition
,它包含一個屬性public String OZ { get; set; }
public String OZ { get; set; }
public String OZ { get; set; }
。 應用程序讀取.txt和.xml文件,OZ從這些文件中獲取值。 我需要將OZ綁定到comboBox:
<ComboBox x:Name="OZs" SelectionChanged="OZs_SelectionChanged" Margin="-10,0,10,1" Grid.Column="0" Grid.Row="1" Height="27" VerticalAlignment="Bottom">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding OZ}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
如您所見,我試圖使用DataTemplate實現數據綁定,但是它不起作用。 我知道可以用ItemsSource實現數據綁定,但是為此,我需要一個ObservableCollection,我沒有它,也不知道如何從OZ創建它。 我已經看到了很多示例,其中ObservableCollection是硬編碼的,並且我了解在對其進行硬編碼時如何使用它,但是我不知道該怎么做。
抱歉,如果解釋不清楚,我是WPF的新手。 我對這個問題很迷失。 任何幫助,將不勝感激。
編輯:根據@ Xiaoy312的答案,我添加了以下代碼:
public IEnumerable<LPosition> OZList { get; set; }
public FormelAssistent()
{
InitializeComponent();
this.DataContext = this;
OZs.ItemsSource = OZList;
}
和XAML:
<ComboBox x:Name="OZs"
SelectionChanged="OZs_SelectionChanged"
Margin="-10,0,10,1"
Grid.Column="0"
Grid.Row="1"
Height="27"
VerticalAlignment="Bottom"
ItemsSource="{Binding OZList}"
DisplayMemberPath="OZ" />
但這不起作用:(
您需要提供一個內容列表(選項),以便ComboBox
通過其ItemsSource
屬性進行選擇。 您不一定需要使用ObservableCollection
支持它。 僅當您計划在顯示視圖時添加/刪除集合時。 任何IEnumerable
都可以工作。
<ComboBox x:Name="OZs"
ItemsSource="{Binding ListOrIEnumerableOfLPosition}"
DisplayMemberPath="OZ" <- you can also use this instead of setting an item template, unless you need something complex
...>
...
</ComboBox >
如果像這樣在類上實現INotifyPropertyChanged
接口,它應該可以工作。
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string PropertyName = "")
{
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
}
private IEnumerable<string> _oz;
public IEnumerable<string> Oz
{
get
{
return _oz;
}
set
{
_oz = value;
NotifyPropertyChanged("Oz");
}
}
如果碰巧正在使用依賴項對象,則可以改用依賴項屬性。 如果有選擇,這將是我的首選。
public IEnumerable<string> Oz
{
get { return (IEnumerable<string>)GetValue(OzProperty); }
set { SetValue(OzProperty, value); }
}
public static readonly DependencyProperty OzProperty = DependencyProperty.Register("Oz", typeof(IEnumerable<string>), typeof(MainWindow), new PropertyMetadata(null));
值得指出的是,如果容器未實現INotifyCollectionChanged
(例如ObservableCollection
),則當整個列表被分配替換時,您只會看到ComboBox
更新。
如果您確實不能使用ObservableCollection
,則可以在get和set中進行通知。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.