私はWPFに新しいので、私は非常に明白な何かを欠落している必要があります。WPFバインドコンボボックスの選択項目をリストビューの現在の項目
私はこのシンプルなセットアップがあります。私が達成したい何
public partial class MainWindow : Window
{
public ObservableCollection<Student> Students { get; set; }
public ObservableCollection<Student> ClassroomStudents { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
Students = new ObservableCollection<Student>();
Students.Add(new Student { ID = 1, Name = "John" });
Students.Add(new Student { ID = 2, Name = "Paul" });
Students.Add(new Student { ID = 3, Name = "Ringo"});
Students.Add(new Student { ID = 4, Name = "George" });
ClassroomStudents = new ObservableCollection<Student>();
ClassroomStudents.Add(Students[0]); //View binds it ok at startup (one way)
ClassroomStudents.Add(Students[1]); //View binds ut ok at startup (one way)
}
public class Student : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public int ID { get; set; }
public string Name { get; set; }
}
private void bOK_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(ClassroomStudents[0].Name);
}
はClassroomStudentsコレクションを表示し、コレクションアイテムにバインドする必要があります各項目のコンボボックスを追加することです。
<Grid>
<ListView x:Name="SortBy" ItemsSource="{Binding ClassroomStudents}" Grid.Column="0">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" Width="80">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ComboBox
ItemsSource="{Binding Students, RelativeSource={ RelativeSource AncestorType=Window}}"
DisplayMemberPath="Name"
SelectedItem="{Binding Path=.,Mode=TwoWay}"
>
</ComboBox>
<!--<Label Content="{Binding}"></Label>-->
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
<!--OK/CANCEL BUTTONS-->
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Grid.Row="1" Margin="0,10,0,0">
<Button x:Name="bOK" IsDefault="True" Margin="10" Width="100" Click="bOK_Click">OK</Button>
<Button x:Name="bCancel" IsCancel="True" Margin="10" Grid.Column="1" Width="100" Click="bCancel_Click">Cancel</Button>
</StackPanel>
</Grid>
これは、1つの方法で細かいバインド:
私はコンボボックス内の別の学生を選択した場合はモデルのコレクションの値は変更されません:
MessageBox.Show(ClassroomStudents[0].Name); //Always return John
私はプロパティ(すなわちID)にバインドするように示唆している答えを見つけましたが、コレクションItem(Student)にバインドしたいと思います。
ありがとう、 Rodo。
選択した項目を含む「Student」タイプのプロパティ「ChosenStudent」を作成します。このように 'SelectedItem =" {Binding Path = DataContext.ChosenStudent、Mode = TwoWay、RelativeSource = {RelativeSource FindAncestor、AncestorType = {x:Type ListView}}}} "のように使用します。 – AnjumSKhan
_ "モデルのコレクション値は変更されません" _ - それはなぜですか?コンボボックスの選択を変更してもコレクションの順序は変わらないので、なぜClassroomStudents [0]は以前とは違う 'Student'オブジェクトを返すのでしょうか?あなたの 'ComboBox'コントロールが' ClassroomStudents'コレクションではなく 'Students'コレクションにバインドされているように見えることさえもカウントしません。確かに、あなたが期待していることや起こってほしいことが何であるか、なぜ、なぜ、特に、あなたが既に 'SelectedItem'プロパティを(前のコメントごとに)バインドするための別のプロパティを除外しているとすれば、 –
あなたは-wayは現在のDataContextをバインドし、コンテキスト内のプロパティのみをバインドします。あなたはバインディング '{Binding Path =。、Mode = TwoWay}'で警告またはエラーを受け取るべきです – grek40