WPF绑定TwoWay DataGrid

时间:2015-11-26 22:45:03

标签: wpf database binding two-way-binding

我正在制作简单的wpf项目,必须连接到DB并将其绑定到DataGrid。 问题是:我可以显示来自数据库的数据,但我无法更新它。我一直在寻找答案,尝试了100种不同的东西,我不知道它能是什么。

我的xaml数据网格:

<Grid>
        <DataGrid x:Name="dataGrid1" ItemsSource="{Binding Path=GridData, Mode=TwoWay,  UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="0"    VerticalAlignment="Stretch"/>

    </Grid>

我的观点

    class View
    { 
        SqlConnection con;
        DataTable dt = new DataTable("emp");
        SqlDataAdapter da;
        SqlCommandBuilder builder;
        public DataView GridData
        {
            get
            {

                con = new SqlConnection(@"Server=MAXMAD-\R;Initial Catalog=WOC;Integrated Security=True");
                try
                {
                    con.Open();
                    string Get_Data = "SELECT * FROM Player";

                    SqlCommand cmd = con.CreateCommand();
                    cmd.CommandText = Get_Data;

                    da = new SqlDataAdapter(cmd);
                    builder = new SqlCommandBuilder(da);
                    da.Fill(dt);
                }
                catch (SqlException ex)
                {
                    MessageBox.Show("Error occured, can not connect to db!");
                    return null;
                }
                return dt.DefaultView;
            }
            set
            {   
                da.Update(dt);
            }
        } 
    }

背后的代码

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent(); 
            View myView = new View();
            DataContext = myView;
        }

    }

1 个答案:

答案 0 :(得分:1)

找到它,我不知道为什么,但设置的GridData没有被调用,所以我添加了一个委托:

dt.RowChanged+= new DataRowChangeEventHandler(delegate(object sender, DataRowChangeEventArgs args) { da.Update(dt); });