如何在向DB中添加新项目后自动更新列表视图

时间:2013-03-07 08:06:33

标签: c# wpf listview

我正在使用C#WPF MVVM。所以在XAML中有一个listview,它绑定到一个对象,用于根据tab显示sql数据库中的不同信息。

例如。我有两种形式:一种是显示信息,另一种是用于输入信息。在以另一种形式输入新信息后,如何以一种形式自动更新列表视图?因为现在我必须切换标签以更新列表视图。

2 个答案:

答案 0 :(得分:1)

该元素的

绑定方向应该暴露给 TwoWay (Mode = TwoWay)

像这样:

  

              X:NAME = “清单”               ItemsSource =“{Binding .......,Path = .........,Mode = TwoWay}}”...... ......

     

除了默认绑定(单向)之外,您还可以将绑定配置为双向,一种方式来源,等等。这是通过指定Mode属性来完成的。

OneWay :导致对source属性的更改以自动更新目标属性,但源不会更改 TwoWay :源或目标中的更改会自动导致对另一个的更新 OneWayToSource :导致更改目标属性以自动更新源属性,但目标不会更改 OneTime :仅在第一次更改源属性时自动更新目标属性,但源不会更改,后续更改不会影响目标属性

你可以看一下:http://msdn.microsoft.com/en-us/library/ms752347.aspx

答案 1 :(得分:1)

在表单中输入新信息后,尝试调用自己的方法,这会将您的信息更新为列表视图。 所以你可以使用一些事件,例如。当您单击将新数据添加到表单中的按钮时,可以调用DataContentChanged或您的更新方法。 刷新方法的示例应如下所示:

public void lbRefresh()        
{
    //create itemsList for listbox
    ArrayList itemsList = new ArrayList();
    //count how many information you wana to add
    //here I count how many columns I have in dataGrid1
    int count = dataGrid1.Columns.Count;
    //for cycle to add my strings of columns headers into an itemsList
    for (int i = 0; i < count; i++)
    {
        itemsList.Add(dataGrid1.Columns[i].Header.ToString());
    }
    //simply refresh my itemsList into my listBox1
    listBox1.ItemsSource = itemsList;
}

编辑:要完成并解决您的问题,请尝试使用以下代码段:

//some btn_Click Event in one window 
//(lets say, its your callback " to update" button in datagrid)
private void Button_Click_1(object sender, RoutedEventArgs e)
{
    //here you doing somethin
    //after your datagrid got updated, try to store the object, 
    //which u want to send into your eg. listbox

    data[0] = data; //my stored data in array

    //for better understanding, this method "Button_Click_1" is called from Window1.xaml.cs
    //and I want to pass information into my another window Graph1.xaml.cs

    //create "newWindow" object onto your another window and send "data" by constuctor
    var newWindow = new Graph1(data); //line *
    //you can call this if u want to show that window after changes applied
    newWindow.Show();
}

之后,您的Graph1.xaml.cs应如下所示:

public partial class Graph1 : Window
{//this method takes over your data u sent by line * into previous method explained
    public Graph1(int[]data) 
    {
        InitializeComponent();
        //now you can direcly use your "data" or can call another method and pass your data into it
        ownListBoxUpdateMethod(data);

    }
    private void ownListBoxUpdateMethod(int[] data)
    {
        //update your listbox here and its done ;-)
    }
相关问题