从ListView WPF更新对象

时间:2014-08-11 11:45:18

标签: c# wpf listview data-binding

我有一个与列表视图一起显示的班级Product,在此列表视图中,我有一个代表ProductOwner的文本框。我无法实现的是从列表视图更新产品对象。很多人会说为什么不使用DataGrid?因为我想尝试使用listview。

我的XAML代码:

<Window
x:Class="WpfApplication4.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow">

<Grid>


    <ListView Name="ListView">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Name" Width="100"  DisplayMemberBinding="{Binding Name}"/>
                <GridViewColumn Header="Reference" Width="100" DisplayMemberBinding="{Binding Reference}" />
                <GridViewColumn Header="Owner" Width="100">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBox Width="90" Name="TextBox"></TextBox>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>
    <Button Name="Button" Content="Submit" Width="120" Height="25" Background="Azure" Click="Button_OnClick"></Button>
</Grid>

此按钮用于从当前产品更新ProductOwner。

代码背后:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        Width = SystemParameters.PrimaryScreenWidth - 100;
        Height = SystemParameters.PrimaryScreenHeight - 100;
        Product product = new Product
        {
          Name  = "name1",
          Reference = "reference1",
          Owner = "owner1"
        };
        Product product2 = new Product
        {
            Name = "name2",
            Reference = "reference2",
            Owner = ""
        };


        List<Product> list = new List<Product>();
        list.Add(product);
        list.Add(product2);
        InitializeComponent();
        ListView.ItemsSource = list;
    }


    private void Button_OnClick(object sender, RoutedEventArgs e)
    {
        //update product1 and product2

    }
}

在Button OnClick事件中,文本框中的值将更新对象的值。 我知道这个问题已经在stackoverflow上,但它并不能满足我的需求。

1 个答案:

答案 0 :(得分:1)

您需要将Text的{​​{1}}属性绑定到您的类的匹配属性(TextBox):

Product.Owner

修改

<TextBox Width="90" Name="TextBox" Text="{Binding Owner, Mode=TwoWay}" /> 失去焦点时,属性会更新。通过将绑定中的TextBox设置为UpdateSourceTriggerPropertyChanged,可以更改此行为。

有关详细信息,请参阅:http://msdn.microsoft.com/en-us/library/ms754356%28v=vs.110%29.aspx