选择 Division 时,ComboBox 类别上的绑定不会更新。
选择一个部门后,ProjectCategories 属性会填充两个结果,但视图不会更新。
如果我将 ProjectCategories 作为参考发送到 ProjectCategoriesGetByDivisionId() ,那么绑定会更新。
我不想传递对我的模型和数据类的引用。如何在不更改模型和数据类的情况下更新绑定?
这是更改类别组合框绑定值的 Divisions ComboBox。
<ComboBox x:Name="Divisions" ItemsSource="{Binding Divisions}" DisplayMemberPath="Name" SelectedValuePath="DivisionId">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<cmd:EventToCommand Command="{Binding DivisionChanged}" CommandParameter="{Binding ElementName=Divisions, Path=SelectedItem}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
未更新的 ComboBox
<ComboBox x:Name="Categories" ItemsSource="{Binding Categories}" DisplayMemberPath="Name" SelectedValuePath="CategoryId" />
触发 Divisions SelectedChanged 事件时触发的方法。
private void DivisionChanged(Division d)
{
ProjectCategories = ProjectCategory.GetByDivisionId(d.DivisionId);
}
ComboBox 绑定到的 ViewModel 属性
public ObservableCollection<ProjectCategory> ProjectCategories
{
get { return projectCategories; }
set
{
projectCategories = value;
if (base.PropertyChangedHandler != null)
base.PropertyChangedHandler(this, new PropertyChangedEventArgs("ProjectCategories"));
}
}
被调用的模型方法
public static ObservableCollection<ProjectCategory> GetByDivisionId(int divisionId)
{
return ProjectData.ProjectCategoriesGetByDivisionId(divisionId);
}
我认为其余的都是不言自明的。
public static ObservableCollection<ProjectCategory> ProjectCategoriesGetByDivisionId(int divisionId)
{
ObservableCollection<ProjectCategory> projectCategory = new ObservableCollection<ProjectCategory>();
SqlConnection conn = null;
try
{
conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("TRK_ProjectCategory_GetByDivisionId", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@DivisionId", SqlDbType.Int).Value = divisionId;
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
projectCategory.Add(ObjectConstructors.ProjectCategoryConstructor(sdr));
}
catch (Exception ex)
{
ErrorHandler.EmailLog("MineralsData", "public static ObservableCollection<ProjectCategory> ProjectCategoriesGetByDivisionId(int divisionId)", ex.ToString(), string.Empty);
throw ex;
}
finally
{
if (conn != null)
conn.Close();
conn = null;
}
return projectCategory;
}
public static ProjectCategory ProjectCategoryConstructor(SqlDataReader dr)
{
ProjectCategory ec = new ProjectCategory();
ec.CategoryId = dr["CategoryId"].SDR_GetInt();
ec.Name = dr["Name"].SDR_GetString();
ec.Description = dr["Description"].SDR_GetString();
ec.LastModified = dr["LastModified"].SDR_GetDateTime();
ec.ModifiedBy = dr["ModifiedBy"].SDR_GetString();
return ec;
}
谢谢你的帮助。