如何绑定到 ObservableCollection 的一个元素

Fly*_*FoX 3 c# data-binding wpf

我有一个 ObservableCollection 并且想要将一个文本框绑定到该集合的特定元素。ObservableCollection 中的项目属于实现 INotifyPropertyChanged 的​​类型。

我曾想过创建一个从 ObservableCollection 中选择正确元素的属性,但是当集合中的相应元素发生更改时,我必须使该属性实现,我不确定这是否是正确的方法。

Rui*_*Rui 5

通常,特别是如果您使用 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;
}
Run Code Online (Sandbox Code Playgroud)

您的窗口对象 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>
Run Code Online (Sandbox Code Playgroud)

以及您刚刚设置数据上下文的代码隐藏:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new ProductsViewModel();
    }
}
Run Code Online (Sandbox Code Playgroud)

每当您在列表框中选择产品时,文本框都会更新为所选产品,如果您更改文本框中的产品(如果产品正确实现 INotifyPropertyChanged),列表框中的项目也将更新。

显然,您只能使用代码隐藏来实现这一切,但出于以下解释的几个原因:http : //msdn.microsoft.com/en-us/magazine/dd419663.aspx,最好有一个 ViewModel


sa_*_*213 5

如果您需要的项目是通过索引指定的,您可以使用索引进行访问

 <TextBlock Text="{Binding MyItemsSource[2]}" />
Run Code Online (Sandbox Code Playgroud)