【问题标题】:How to bind a datagrid row with text boxes in wpf mvvm如何在 wpf mvvm 中将数据网格行与文本框绑定
【发布时间】:2015-08-19 01:28:16
【问题描述】:

我有一个包含一些产品详细信息的 DataGrid,当我双击数据网格中的特定产品时,我需要将产品详细信息加载到一些文本框中。

提前致谢。

【问题讨论】:

  • 你尝试了什么?
  • 我是 wpf 的初学者,所以我没有尝试任何东西,而是在互联网上搜索...... :(

标签: wpf mvvm binding datagrid


【解决方案1】:

欢迎来到 StackOverflow!通常人们不会在没有以下内容的情况下回答问题。

  • 对您尝试做的事情的清晰总结。
  • 所有相关代码
  • 您遇到的任何异常
  • 您使用的所有研究链接以了解您所在的位置

也就是说,我会给你演示一下你的要求。

这里是 XAML

<Window x:Class="datagriddemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ViewModel="clr-namespace:datagriddemo"
        Title="MainWindow" Height="350" Width="420" Background="Gray">
    
    <!--This is where we define the resource that the XAML here is going to
    use. As you can see, I am importing our view model-->
    <Window.Resources>
        <ViewModel:ProductGridViewModel x:Key="ProductViewModel"/>
    </Window.Resources>
    
    
    <!--This is the main layout of the XAML. In the Grid below,
    I set the "DataContext" to our static resource we just defined above.
    What this does is tell everyone inside this grid, "If you don't define
    your own data context, you're going to use mine" Because of this, all
    of the elements inside this grid will have access to the public properties
    of the ViewModel-->
    <Grid DataContext="{StaticResource ResourceKey=ProductViewModel}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="300"/>
            <ColumnDefinition Width="100"/>
        </Grid.ColumnDefinitions>
        
        <!-- This is the datagrid that we are displaying. The two important things
        to note here are "ItemsSource" and "SelectedItem". "ItemsSource" is the collection
        that we want to display in our grid. This is where are product models are stored.
        SelectedProduct is going to be where the selected grid row is stored so we can
        access its data with the text boxes defined below. -->
        <DataGrid 
            Width="500" 
            Grid.Column="0"
            AutoGenerateColumns="False"                        
            ItemsSource="{Binding Products}"
            SelectedItem="{Binding SelectedProduct, Mode=TwoWay}">
            <DataGrid.Columns>
                <DataGridTextColumn IsReadOnly="True"  Header="Product ID" Binding="{Binding ProductID, UpdateSourceTrigger=PropertyChanged}" />
                <DataGridTextColumn IsReadOnly="True"  Header="Product Name" Binding="{Binding ProductName, UpdateSourceTrigger=PropertyChanged}" />
                <DataGridTextColumn IsReadOnly="True"  Header="Total Sold" Binding="{Binding TotalSold, UpdateSourceTrigger=PropertyChanged}" />
            </DataGrid.Columns>
        </DataGrid>
        
        <!-- This stack panel contains the text boxes we are going to use to edit our data. Notice that the 
        bindings point to SelectedProduct.Property. This is because we are accessing properties inside of 
        the SelectedProduct property in our ViewModel. When we edit these text boxes the data in the grid
        will automatically change. -->
        <StackPanel Height="100" Background="Wheat" Margin="10" Orientation="Vertical" Grid.Column="1">
            <TextBlock FontWeight="Bold" Width="100" TextWrapping="Wrap">Update your product info!</TextBlock>
            <TextBox Width="100" Text="{Binding SelectedProduct.ProductName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
            <TextBox Width="100" Text="{Binding SelectedProduct.TotalSold, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
        </StackPanel>
    </Grid>
</Window>

接下来是我们的 ViewModel。如果视图是蛋糕上的糖霜,那么您可以将视图模型视为布丁周围的蛋糕。您的视图模型是您的逻辑所在。它会进行排序、处理和其他操作。

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace datagriddemo
{
    public class ProductGridViewModel
    {
        private ProductModel _SelectedProduct;
        private ObservableCollection<ProductModel> _Products;


        /// <summary>
        /// Notice that though this updates the grid as you
        /// add or remove elements, it doesn't call onproperty
        /// changed in the setter... Magic? Nope, Observable
        /// collections call OnPropertyChanged for you.
        /// 
        /// Caveat: They will NOT call on property changed
        /// for you if you do Products = new ObservableCollection...
        /// Only when you do Products.Add(yourProduct)...
        /// </summary>
        public ObservableCollection<ProductModel> Products
        {
            get { return _Products; }
            set { _Products = value; }
        }

        

        /// <summary>
        /// This is the selected row in the grid. It automatically changes
        /// when you select new rows because we set the grid SelectedItem property 
        /// to Mode=TwoWay
        /// </summary>
        public ProductModel SelectedProduct
        {
            get { return _SelectedProduct; }
            set { _SelectedProduct = value; }
        }
        

        /// <summary>
        /// View Models constructor. It get's called automatically when the view 
        /// is initialized because we declared it as a static resource in the XAML.
        /// </summary>
        public ProductGridViewModel()
        {
            //DONT FORGET TO NEW UP YOUR OBSERVABLE COLLECTIONS!! 
            Products = new ObservableCollection<ProductModel>();

            //Don't forget to generate the data!
            GenerateProducts();
        }

        /// <summary>
        /// Use this method to generate dummy data
        /// </summary>
        private void GenerateProducts()
        {
            for (int x = 0; x < 100; x++)
            {
                
                this.Products.Add(new ProductModel(x,"Product #"+x,x+50));
            }
        }
        
    }
}

终于有了你的模型。这是您的实际数据。这,没错,就是你的布丁。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace datagriddemo
{
    public class ProductModel : INotifyPropertyChanged
    {
        private Int32 _ProductID;
        private String _ProductName;
        private Int32 _TotalSold;


        /// <summary>
        /// Note for the properties below:
        /// Notice that first, the property names match those bound in the XAML
        /// This is all part of the grand scheme.
        /// 
        /// When the OnProperty changed is called, the UI knows to go search for
        /// those properties. It's important that these all have the correct spelling
        /// and casing.
        /// </summary>

        public Int32 TotalSold
        {
            get { return _TotalSold; }
            set 
            { 
                _TotalSold = value;
                OnPropertyChanged("TotalSold");
            }
        }
        

        public String ProductName
        {
            get { return _ProductName; }
            set 
            { 
                _ProductName = value;
                OnPropertyChanged("ProductName");
            }
        }


        public Int32 ProductID
        {
            get { return _ProductID; }
            set 
            { 
                _ProductID = value;
                OnPropertyChanged("ProductID");
            }
        }
        

        /// <summary>
        /// Just a normal constructor to load up our properties.
        /// </summary>
        /// <param name="productID"></param>
        /// <param name="productName"></param>
        /// <param name="totalSold"></param>
        public ProductModel(Int32 productID, String productName, Int32 totalSold)
        {
            this.ProductID = productID;
            this.ProductName = productName;
            this.TotalSold = totalSold;
        }

        /// <summary>
        /// This is for updating the UI
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// When a property changes in this object, if you want it reflected on the 
        /// UI you need to call this function
        /// </summary>
        /// <param name="propertyName"></param>
        public void OnPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

最后是预期的结果

在第一张图片中,我们看到我们的网格加载了新数据

如果你点击一行,你会看到它的数据填充在侧面的两个文本框中。

最后,如果您更改文本框中的数据,您将在网格中看到它立即更新。

就是这样!一个完整的 MVVM 数据网格到文本框和返回解决方案。希望这可以帮助。请记住我所说的关于您作为提问者的期望并玩得开心!欢迎使用 WPF 和 MVVM。

【讨论】:

  • 只有双击特定产品时才能触发此绑定...?
  • 这有点棘手。您需要研究事件触发器并提出不同的绑定方法。简而言之,这并不容易,但是是的,这是可能的。
  • @MubarackAli 如果此示例对您有所帮助并回答了您的问题,请确保单击选中此答案的复选标记。谢谢!
  • 感谢您的帮助... :)
猜你喜欢
  • 2014-01-29
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
  • 2015-10-16
  • 1970-01-01
  • 2012-11-24
  • 2012-01-15
  • 2013-12-04
相关资源
最近更新 更多