我有這個問題,必須綁定列表視圖中嵌入的組合框的選定值。我在顯示組合框中的項目時沒有問題。但是,我希望我能夠通過單擊按鈕來指定組合框應該顯示的內容(從它保存的項目中)。我認爲在這個問題上有幾個帖子,但是,我無法得到我想要的。這是我的代碼。在列表視圖中綁定到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