[英]WPF ComboBox does not display content
我的xaml文件上有一個簡單的組合框:
<ComboBox Name="environmentComboBox" Grid.Column="1" Grid.Row="0" Margin="2"
SelectionChanged="environmentComboBox_SelectionChanged"
ItemsSource="{Binding Path=Test}"/>
以下是其內容的代碼:
private List<string> test = new List<string>(){"1", "2"};
public List<string> Test
{
get
{
return test;
}
set
{
test = value;
}
}
我嘗試調試該應用程序,但ComboBox沒有顯示任何內容。 但是當我檢查Test是否包含內容時,它會顯示兩個字符串。
必須將視圖DataContext
設置為包含List<T>
的Model/Window
?
如果不是,則需要告訴View使用什么DataContext
,下面是一個WPF窗口的快速示例,並將xamls DataContext
設置為View后面的代碼。
還建議在綁定集合時使用ObservableCollection<T>
,因為添加和刪除項將自動更新ComboBox
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this; // set datacontext
}
private ObservableCollection<string> test = new ObservableCollection<string>() { "1", "2" };
public ObservableCollection<string> Test
{
get { return test; }
set { test = value; }
}
}
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<ComboBox ItemsSource="{Binding Path=Test}"/>
</StackPanel>
</Window>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.