使用Update中的MVVM在Dataform Silverlight中进行数据绑定组合框

时间:2011-02-18 14:39:33

标签: silverlight data-binding mvvm combobox dataform

我有Master / Detail - datagrid / dataform,在selectform项目之后显示在dataform中进行更新,但是我遇到了数据绑定或用部门填充combox并将SelectedEmployee.departmentid设置为selectedvalue的问题。

现在有两个问题:

1。在EmployeeViewModel中,这段代码不起作用,问题为何?

  private ObservableCollection<department> _departments;
        public ObservableCollection<department> Departments
        {
            get { return _departments; }
            set
            {
                _departments = value;
                RaisePropertyChanged("Departments");
            }
        }

但是这段代码工作正常

   private ObservableCollection<department> _departments;
        public ObservableCollection<department> Departments
        {
            get {

                if (_departments == null)
                {
                    _departments = new ObservableCollection<department> {
                        new department()
                        { id = 1, departmentname = "Technical " + 1, },
                        new department()
                        { id = 2,  departmentname = "Technical " + 2, },
                        new department()
                        { id = 3,  departmentname = "Technical " + 3, }                    
                    };
                }
                  return _departments; 
            }
            set
            {
                _departments = value;
                RaisePropertyChanged("Departments");
            }
        }

2。 DataForm内部和外部的Combobox行为是不同的。外面它有效,内部没有。我认为这里需要在ItemsSource中使用Source,但我不知道如何。那么另一个问题是如何解决它?

employeeView.xaml

<navigation:Page    xmlns:local="clr-namespace:departmentTechManager"
            x:Class="departmentTechManager.Views.employeeView" 
                   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
                   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
                   xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                   mc:Ignorable="d"
                   xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
                   d:DesignWidth="820" d:DesignHeight="780"
                   Title="employees"
                   Style="{StaticResource PageStyle}"

            xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" 
            xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
            xmlns:mvvmlightcmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.SL4"
            xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
            xmlns:dataformtoolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.DataForm.Toolkit" 

            DataContext="{Binding employeeStatic, Source={StaticResource Locator}}">

<data:DataGrid Grid.Row="0" x:Name="dgEmployees" CanUserSortColumns="true"
                                             IsReadOnly="true" AutoGenerateColumns="true"
                                             ItemsSource="{Binding Employees}"
                                             SelectedItem="{Binding SelectedEmployee, Mode=TwoWay}"  Margin="0,36,-123,0"></data:DataGrid>
<dataformtoolkit:DataForm x:Name="dfDetails"
      CurrentItem="{Binding SelectedEmployee}" AutoGenerateFields="False"
      CommitButtonContent="Save" CommandButtonsVisibility="Edit, Commit, Cancel">
      <dataformtoolkit:DataForm.EditTemplate>
                      <DataTemplate>
                        <StackPanel>
                           <dataformtoolkit:DataField Label="name">
    <TextBox Text="{Binding name, Mode=TwoWay}" /></dataformtoolkit:DataField>

      <dataformtoolkit:DataField Label="departments">


            <ComboBox ItemsSource="{Binding Departments}"  
        DisplayMemberPath="departmentname"
            SelectedValuePath="id"  
            SelectedValue="{Binding Path=SelectedEmployee.departmentid, Mode=TwoWay}" />


     </dataformtoolkit:DataField>
      </StackPanel>
     </DataTemplate>
            </dataformtoolkit:DataForm.EditTemplate>
            <i:Interaction.Triggers><i:EventTrigger EventName="EditEnded">
                <mvvmlightcmd:EventToCommand Command="{Binding SaveEmployeesCommand}"/>
               </i:EventTrigger></i:Interaction.Triggers>
            </dataformtoolkit:DataForm>

在ViewModelLocator.cs中:

 public ViewModelLocator()
        {

            _sp = ServiceProviderBase.Instance;

            Createdepartment();

            Createemployee();

        }

#region EmployeeViewModel
private static EmployeeViewModel _employee;

public static EmployeeViewModel employeeStatic
{
    get
    {
        if (_employee == null)
        {
            Createemployee();
        }

        return _employee;
    }
}

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
    "CA1822:MarkMembersAsStatic",
    Justification = "This non-static member is needed for data binding purposes.")]
public EmployeeViewModel employee
{
    get
    {
        return employeeStatic;
    }
}

public static void Clearemployee()
{
    //do it later
    //_employee.Cleanup();
    _employee = null;
}

public static void Createemployee()
{
    if (_employee == null)
    {
        _employee = new EmployeeViewModel(_sp.PageConductor, _sp.EmployeeDataService);
    }
}
#endregion

#region DepartmentViewModel
        private static DepartmentViewModel _department;

        public static DepartmentViewModel departmentStatic
        {
            get
            {
                if (_department == null)
                {
                    Createdepartment();
                }

                return _department;
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
            "CA1822:MarkMembersAsStatic",
            Justification = "This non-static member is needed for data binding purposes.")]
        public DepartmentViewModel department
        {
            get
            {
                return departmentStatic;
            }
        }

        public static void Cleardepartment()
        {
            //do it later
            //_department.Cleanup();
            _department = null;
        }

        public static void Createdepartment()
        {
            if (_department == null)
            {
                _department = new DepartmentViewModel(_sp.PageConductor, _sp.DepartmentDataService);
            }
        }

        #endregion

有人可以帮助我吗?

combox只是空的。但是现在我可以像部门那样填充它:

departmentTechManagerDomainService.metadata.cs

 [MetadataTypeAttribute(typeof(employee.employeeMetadata))]
        public partial class employee
        {
     [Include]
     public department department { get; set; }
     public Nullable<int> departmentid { get; set; }
     public string name { get; set; }
        } 

departmentTechManagerDomainService.cs

public IQueryable<employee> GetEmployees()
        {return this.ObjectContext.employees.Include("department").OrderBy(e=>e.name);}

这里是ViewModel代码:

        private ObservableCollection<department> _departments;
        public ObservableCollection<department> Departments
        {
            get { return _departments; }
            set
            {
                _departments = value;
                RaisePropertyChanged("Departments");
            }
        }

        private department _selectedDepartment;
        public department SelectedDepartment
        {
            get { return _selectedDepartment; }
            set
            {
                _selectedDepartment = value;
                RaisePropertyChanged("SelectedDepartment");
            }
        }

private void InitializeModels()
        {
            Employees = new ObservableCollection<employee>();
            SelectedEmployee = new employee();
            NewEmployee = new employee();

            //new
            Departments = new ObservableCollection<department>();
            SelectedDepartment = new department();

        }

private void GetEmployeesCallback(IEnumerable<employee> employees)
        {
            if (employees != null)
            {
                foreach (var employee in employees)
                {
                    Employees.Add(employee);
                    //new
                    if (!Departments.Contains(employee.department))
                        Departments.Add(employee.department);

                }
                if (Employees.Count > 0)
                {
                    SelectedEmployee = Employees[0];
                }

            }
        }

我使各部门区别开来,但这里只有那些已经被选中的部门,但是这里还没有那些尚未被选中的部门,并且仍然没有组装部门在DataForm中。 ?!

3 个答案:

答案 0 :(得分:1)

第二个问题 - 看起来数据形式内外的combobox会收到不同的DataContext,因此会尝试在不同来源上找到Departments属性。由于您尚未显示大部分ViewModel,因此尚不清楚如何修复它。

注意VS output窗口,它通常提供有关绑定错误的非常详细的信息,我假设你的情况有绑定错误。

尝试按以下方式修改与部门相关的绑定:

<ComboBox ItemsSource="{Binding DataContext.Departments, RelativeSoruce={RelativeSource AncestorType={x:Type localViews:employeeView}}}" />

localViews应该是departmentTechManager.Views的xml命名空间。尝试SelectedItem绑定的相同技巧。

答案 1 :(得分:1)

我已经得到了这个问题的解决方案。 here它是。

答案 2 :(得分:1)

在编辑模板中,必须使用ViewModel Name

提及Source
   <ComboBox Grid.Row="2" Grid.Column="1"
    ItemsSource="{Binding Path=Accounts, Source={StaticResource MyAccountViewModel}, Mode=TwoWay}" />