MVVM:如何給一個列表綁定資料

來源:互聯網
上載者:User

使用MVVM的方式給一個gridview綁定資料來源

是telerik控制項

1.定義的實體DocRegister

ObservableCollection<DocRegister> _dataSouce;

2.定義實體的屬性
 public ObservableCollection<DocRegister> DataSouce
        {
            get { return _dataSouce; }
            set
            {
                if (!ReferenceEquals(_dataSouce, value))
                {
                    _dataSouce = value;
                    this.RaisePropertyChanged(() => this.DataSouce);
                }
            }
        }
3.記得當前類繼承自NotificationObject

4.所有的命名空間:
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Practices.Prism.ViewModel;
using System.Collections.ObjectModel;
using Microsoft.Practices.Prism.Commands;

5.建構函式的時候用WCF從伺服器端把資料那過來

        public DocRegisterNavigateViewModel()
        {
            client = InnerHelper.CreateDocRegisterManageServiceClient();
            client.GetDocRegisterListCompleted += new EventHandler<GetDocRegisterListCompletedEventArgs>(client_GetDocRegisterListCompleted);
            //在什麼時候調用WCF,很有用的
            client.GetDocRegisterListAsync("", "");
        }

        void client_GetDocRegisterListCompleted(object sender, GetDocRegisterListCompletedEventArgs e)
        {
            if (e.Error == null)
            {
            //返回結果               
              DataSouce = e.Result;
            }
            else
            {
                Glodon.Component.Controls.DialogHelper.AlertDialog("擷取資料失敗!", "提示");
            }
        }
6.點擊頁面的查看註冊的事件
   private ICommand _lookCommand;
        public ICommand LookCommand
        {
            get { return _lookCommand ?? (_lookCommand = new DelegateCommand<object>(this.OnLookCommand)); }
        }

7.當點擊”查看“每行串連的時候把值傳過去(建立一個新的頁面,並且把當前選擇的行值傳過去)
    private void OnLookCommand(object obj)
        {
            if (CurrentItem != null)
            {
                AddDOCRegister editWindow = new AddDOCRegister(CurrentItem);
                editWindow.Show();
            }
        }
8.XAML檔案:注意Command的使用

            <TR:RadGridView HorizontalAlignment="Left" Name="radGridView" VerticalAlignment="Top" ItemsSource="{Binding DataSouce,Mode=TwoWay}" SelectedItem="{Binding CurrentItem,Mode=TwoWay}"
                                 AutoGenerateColumns="False" ShowGroupPanel="False"       Grid.Row="1">
                <TR:RadGridView.Columns>

                    <TR:GridViewColumn Header="查看" Width="60" HeaderTextAlignment="Center">
                        <TR:GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <HyperlinkButton Name="ViewButton" Tag="{Binding DocRegisterAdministrativeId}"  Content="查看" Command="{Binding Source={StaticResource DataContextProxy},Path=DataSource.LookCommand}" CommandParameter="{Binding ElementName=ViewButton}"/>
                            </DataTemplate>
                        </TR:GridViewColumn.CellTemplate>
                    </TR:GridViewColumn>

                    <TR:GridViewDataColumn IsReadOnly="True" Header="序號" IsFilterable="False" Width="60"   TextAlignment="Center" HeaderTextAlignment="Center"  />
                    <TR:GridViewDataColumn IsReadOnly="True" DataMemberBinding="{Binding ReceiptDate,Mode=OneWay}" Header="收文日期" IsFilterable="False" Width="150"   HeaderTextAlignment="Center"  />
                    <TR:GridViewDataColumn IsReadOnly="True" DataMemberBinding="{Binding DNumber,Mode=OneWay}" Header="來文字型大小" IsFilterable="False" Width="120"   HeaderTextAlignment="Center"  />
                    <TR:GridViewDataColumn IsReadOnly="True" DataMemberBinding="{Binding DFrom,Mode=OneWay}" Header="來文機關" IsFilterable="False" Width="*"   HeaderTextAlignment="Center"  />
                    <TR:GridViewDataColumn IsReadOnly="True" DataMemberBinding="{Binding DTitle,Mode=OneWay}" Header="檔案標題" IsFilterable="False" Width="*"   HeaderTextAlignment="Center"  />
                    <TR:GridViewDataColumn IsReadOnly="True" DataMemberBinding="{Binding DConfidentialityId,Mode=OneWay}" Header="機密程度" IsFilterable="False" Width="60"   HeaderTextAlignment="Center"  />
                    <TR:GridViewDataColumn IsReadOnly="True" DataMemberBinding="{Binding FileCount,Mode=OneWay}" Header="本文份數" IsFilterable="False" Width="60"   HeaderTextAlignment="Center"  />
                    <TR:GridViewDataColumn IsReadOnly="True" DataMemberBinding="{Binding AttachmentCount,Mode=OneWay}" Header="附件份數" IsFilterable="False" Width="60"   HeaderTextAlignment="Center"  />
                    <TR:GridViewDataColumn IsReadOnly="True" DataMemberBinding="{Binding DState,Mode=OneWay}" Header="狀態" IsFilterable="False" Width="80"   HeaderTextAlignment="Center"  />
                </TR:RadGridView.Columns>
            </TR:RadGridView>

(1)DataContextProxy在頁面開始時有這樣一行代碼,把。CS檔案引入過來,這樣在當前XAML檔案下面可以使用
 <UserControl.Resources>
        <helper:DataContextProxy x:Key="DataContextProxy" />
 </UserControl.Resources>

DataContextProxy的定義

using System;using System.Net;using System.Windows;using System.Windows.Controls;using System.Windows.Documents;using System.Windows.Ink;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Animation;using System.Windows.Shapes;using System.Windows.Data;namespace Glodon.Module.DocRegisterManage.Help{    public class DataContextProxy : FrameworkElement    {        public DataContextProxy()        {            this.Loaded += new RoutedEventHandler(DataContextProxy_Loaded);        }        void DataContextProxy_Loaded(object sender, RoutedEventArgs e)        {            Binding binding = new Binding();            if (!String.IsNullOrEmpty(BindingPropertyName))            {                binding.Path = new PropertyPath(BindingPropertyName);            }            binding.Source = this.DataContext;            binding.Mode = BindingMode;            this.SetBinding(DataContextProxy.DataSourceProperty, binding);        }        public Object DataSource        {            get { return (Object)GetValue(DataSourceProperty); }            set { SetValue(DataSourceProperty, value); }        }        public static readonly DependencyProperty DataSourceProperty =            DependencyProperty.Register("DataSource", typeof(Object), typeof(DataContextProxy), null);        public string BindingPropertyName { get; set; }        public BindingMode BindingMode { get; set; }    }}

9.最主要的一步,把viewmodel與頁面綁定在一起的
在XAML頁面的初始化的時候,給xaml當前的上下文DataContext 指定一個viewmodel:DocRegisterNavigateViewModel

  public partial class DocRegisterNavigateView : UserControl
    {
        public DocRegisterNavigateView()
        {
            InitializeComponent();
            this.DataContext = new DocRegisterNavigateViewModel();     
        }
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.