【问题标题】:databinding combobox in Dataform Silverlight using MVVM in UpdateDataform Silverlight 中的数据绑定组合框在 Update 中使用 MVVM
【发布时间】:2011-06-29 21:07:27
【问题描述】:

我有 Master/Detail – datagrid/dataform 并在选择项目后显示在数据表单中以进行更新,但我在数据绑定或填充组合框时遇到问题,并将 SelectedEmployee.departmentid 设置为 selectedvalue。

这里有 2 个问题:

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 中的部门。 ?!

【问题讨论】:

  • 关于第一个问题 - 它如何不起作用以及在哪种情况下?
  • 我在问题中添加了代码。它在字符串“组合框只是空的。但现在我可以用这样的部门填充它”

标签: silverlight data-binding mvvm combobox dataform


【解决方案1】:

第二个问题 - 看起来combobox 内部和外部数据表单接收不同的DataContext 并因此尝试在不同来源上定位Departments 属性。由于您尚未展示大部分 ViewModel,因此尚不清楚如何修复它。

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

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

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

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

【讨论】:

  • DataContext 的问题与msmvps.com/blogs/deborahk/archive/2009/11/25/… 此处描述的问题相似。但问题是如何在没有 DomainDataSource 的情况下使用 MVVM 方法来做到这一点。我在问题中添加了代码。它在字符串“组合框只是空的。但现在我可以用这样的部门填充它”
  • 我将 xmlns:localViews="departmentTechManager.Views" 声明添加到 标记和 进入DataForm,但现在有3个错误:错误XML命名空间'schemas.microsoft.com/winfx/2006/xaml/presentation'中的类型'RelativeSource'上不存在属性'AncestorType'。错误找不到类型“x:Type”。确认您没有丢失程序集引用并且所有引用的程序集都已构建。
  • 错误在类型“RelativeSource”中找不到属性“AncestorType”。
  • @rojorm,哦,我忘了,可能 Silverlight 不支持这个
【解决方案2】:

我有这个问题的解决方案。 here 是。

【讨论】:

  • 链接已损坏。你能更新一下吗?我有同样的问题。
【解决方案3】:

在编辑模板中,Source 必须与 ViewModel Name 一起提及

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

【讨论】:

    猜你喜欢
    • 2010-12-21
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多