我有这个问题,必须绑定列表视图中嵌入的组合框的选定值。我在显示组合框中的项目时没有问题。但是,我希望我能够通过单击按钮来指定组合框应该显示的内容(从它保存的项目中)。我认为在这个问题上有几个帖子,但是,我无法得到我想要的。这是我的代码。在列表视图中绑定到WPF组合框(2路)
XAML:
<Grid>
<StackPanel Orientation="Vertical">
<ListView
x:Name="OptionsListView"
ItemsSource="{Binding MyObjectCollection}">
<ListView.Resources>
<DataTemplate x:Key="comboBoxTemplate">
<ComboBox
Margin="0,3"
x:Name="MyTypeComboBox"
SelectedValue="{Binding Path=SelectedType, Mode=TwoWay}">
<ComboBoxItem Content="ABC"/>
<ComboBoxItem Content="DEF"/>
<ComboBoxItem Content="XYZ"/>
</ComboBox>
</DataTemplate>
</ListView.Resources>
<ListView.View>
<GridView>
<GridViewColumn Header="Text-Sample"
Width="100">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Combo-Sample"
Width="100"
CellTemplate="{StaticResource comboBoxTemplate}" />
</GridView>
</ListView.View>
</ListView>
<Button Click="Button_Click">Click Me!</Button>
</StackPanel>
</Grid>
C#代码背后:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
OptionsListView.DataContext = this;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//Something here that dictates what should be displayed in the combo box
}
List<MyObject> myObjectCollection = new List<MyObject>();
public List<MyObject> MyObjectCollection
{
get
{
myObjectCollection.Add(new MyObject("One"));
myObjectCollection.Add(new MyObject("Two"));
return myObjectCollection;
}
}
}
public class MyObject : INotifyPropertyChanged
{
private string _name;
public MyObject(string name)
{
// TODO: Complete member initialization
this._name = name;
}
public string Name
{
get
{
return _name;
}
}
string selectedType = string.Empty;
public string SelectedType
{
get
{
return selectedType;
}
set
{
selectedType = value;
this.NotifyChange("SelectedType");
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyChange(params object[] properties)
{
if (PropertyChanged != null)
{
foreach (string p in properties)
{
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
}
}
#endregion
}
我会很高兴,如果有人可以帮我破解这个..
感谢 拉姆
非常感谢Howard ..现在工作正常!显然,我一直在试图设置组合框的值,但没有绑定它。现在,当我指定(如你所建议的)一个绑定到组合框的集合时,它就像魅力一样工作!我对吗?数据绑定到使用ItemSource的组合框是关键吗?非常感谢! – Ram 2011-04-18 16:19:58
:)玩得开心。欢迎您 – Howard 2011-04-18 16:23:31