【发布时间】:2013-11-03 04:39:43
【问题描述】:
我是 WPF 新手。
我正在尝试将字符串集合绑定到组合框。
public ObservableCollection<string> ListString {get; set;}
Binding和datacontext设置如下
<Window
x:Class="Assignment2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:validators="clr-namespace:Assignment2"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
DataContext="{Binding RelativeSource={RelativeSource Self}, Path=.}">
<Grid>
<ComboBox Height="23" HorizontalAlignment="Left" Margin="109,103,0,0" Name="StringComboBox" VerticalAlignment="Top" Width="120" SelectionChanged="StringComboBox_SelectionChanged">
<ComboBox.ItemsSource>
<Binding Path="ListString" BindsDirectlyToSource="True" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"></Binding>
</ComboBox.ItemsSource>
</ComboBox>
我知道这是因为收藏正在更新。如果我写
public MainWindow()
{
InputString = "";
ListString = new ObservableCollection<string>();
ListString.Add("AAA");
ListString.Add("BBB");
ListString.Add("CCC");
InitializeComponent();
}
它确实有效,但如果我将InitializeComponent() 移动到第一行上方,如下所示,它不起作用。
public MainWindow()
{
InitializeComponent();
InputString = "";
ListString = new ObservableCollection<string>();
ListString.Add("AAA");
ListString.Add("BBB");
ListString.Add("CCC");
}
我该怎么办??
【问题讨论】:
-
一个有效,另一个无效。我会选择可行的选项。
-
@Blam 我试图概括这个问题以解决我的另一个问题,其中列表来自 WCF 服务。您仍然建议使用可行的选项吗??
标签: c# wpf binding combobox observablecollection