【问题标题】:Strange ListView.SelectedValue binding issue (At least for me)奇怪的 ListView.SelectedValue 绑定问题(至少对我来说)
【发布时间】:2012-03-14 19:50:43
【问题描述】:

我有一个包含绑定数据的 ListView,以及两个像这样的附加绑定:

    <ListView x:Name="listViewProducts" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" ItemsSource="{Binding Products}" IsSynchronizedWithCurrentItem="True" 
              SelectedItem="{Binding Path=Product, Mode=OneWayToSource}" SelectedIndex="{Binding Path=SelectedProductIndex, Mode=OneWayToSource}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="ID" Width="100" DisplayMemberBinding="{Binding ID}" />
                <GridViewColumn Header="Name" Width="170" DisplayMemberBinding="{Binding Name}" />
                <GridViewColumn Header="Price" Width="100" DisplayMemberBinding="{Binding Price}" />
                <GridViewColumn Header="Reseller" Width="Auto" DisplayMemberBinding="{Binding Reseller}" />
            </GridView>
        </ListView.View>
    </ListView>

像这样,我在 ViewModel 中有必要的 Product 属性。我也有 4 个文本框,例如如下:

    < TextBox Grid.Row="0" Grid.Column="1" x:Name="txtName" ... 
        Text="{Binding Text, Path=Product.Name, Mode=TwoWay}" />

这就是我想要实现的目标: 我只想在用户单击定义如下的按钮时更新列表元素:

    <Button Grid.Row="0" Grid.Column="2" x:Name="btnUpdate" .... 
       Content="Update product" 
       Command="{Binding Path=Update_Command}" 
       CommandParameter="{Binding ElementName=listViewProducts, Path=SelectedIndex}" />

这就是发生的事情:每当我在 listView 中选择一个项目时,文本框都会获得正确的属性。当我更改一个文本框并选择另一个文本框时,模型会立即更新。当SelectedItem与“ OnewayTosource”模式绑定时,这将如何?

【问题讨论】:

    标签: c# binding mvvm .net-4.0


    【解决方案1】:

    在我看来,这是因为您将 SelectedItem 绑定到 ViewModel 中的 Product 属性,在您在 listView 中选择一个项目后,它将通过 listView.SelectedItem 传递对 Product 属性的引用,因此您将获得对您在 Products 集合中拥有的相同对象。之后,您将使用 TwoWay 绑定 (TextBoxes) 并更改 Product 的属性,这将通过引用自动将这些更改反映到 listView。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多