ObservableCollection があり、Textbox をそのコレクションの特定の要素にバインドしたいと考えています。ObservableCollection のアイテムは、INotifyPropertyChanged を実装するタイプです。
ObservableCollection から適切な要素を選択するプロパティを作成することを考えましたが、コレクション内の対応する要素が変更されたときにこのプロパティを認識させる必要があり、これが正しい方法であるかどうかはわかりません。
ObservableCollection があり、Textbox をそのコレクションの特定の要素にバインドしたいと考えています。ObservableCollection のアイテムは、INotifyPropertyChanged を実装するタイプです。
ObservableCollection から適切な要素を選択するプロパティを作成することを考えましたが、コレクション内の対応する要素が変更されたときにこのプロパティを認識させる必要があり、これが正しい方法であるかどうかはわかりません。
通常、特に MVVM を使用する場合は、ObservableCollection を持つ viewModel と、データ バインディングで更新する SelectedItem のプロパティがあります。
たとえば、viewModel は次のようになります。
class ProductsViewModel : INotifyPropertyChanged
{
public ObservableCollection<Product> Products { get; set; }
private Product _selectedProduct;
public Product SelectedProduct
{
get { return _selectedProduct; }
set
{
_selectedProduct = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("SelectedProduct"));
}
}
public ProductsViewModel()
{
Products = new ObservableCollection<Product>();
Products.Add(new Product() { Name = "ProductA" });
Products.Add(new Product() { Name = "ProductB" });
}
public event PropertyChangedEventHandler PropertyChanged;
}
ウィンドウ オブジェクト xaml:
<Window x:Class="ProductsExample.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">
<Grid>
<ListBox HorizontalAlignment="Left" Height="171" Margin="32,29,0,0" VerticalAlignment="Top" Width="176"
ItemsSource="{Binding Products}"
SelectedItem="{Binding SelectedProduct, Mode=TwoWay}"
DisplayMemberPath="Name"
/>
<TextBox HorizontalAlignment="Left" Height="33" Margin="36,226,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="172"
Text="{Binding SelectedProduct.Name, Mode=TwoWay}"/>
</Grid>
</Window>
そして、データコンテキストを設定したコードビハインド:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ProductsViewModel();
}
}
リストボックスで製品を選択すると、選択した製品でテキストボックスが更新され、テキストボックスで製品を変更すると (製品が INotifyPropertyChanged を正しく実装している場合)、リストボックスの項目も更新されます。
明らかに、コード ビハインドを使用するだけでこれらすべてを達成できますが、ここで説明されているいくつかの理由により: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx、ViewModelを使用することをお勧めします。
必要なアイテムがインデックスによって特定されている場合は、インデックスを使用してアクセスできます
<TextBlock Text="{Binding MyItemsSource[2]}" />