0

我有一个数据模板控制的控件,该控件是基于 EF 数据集合生成的,该数据集设置为该控件的 Datacontext。该模板还有一个组合框,里面应该可以将外键值更改为另一个 EF 实体对象。

我正在尝试从 viewModel 加载外键集合

<my:EntryControlBase.Resources>
    <my:ModulesViewModel x:Key="viewModel"/>
</my:EntryControlBase.Resources>

这是数据模板中的控件

<DataTemplate>
            <Grid Name="grdRoles" Background="Gray" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >

                <TextBox Height="23" Text="{Binding Path=Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />


                *<ComboBox Height="25" ItemsSource="{Binding   Source={StaticResource viewModel}, Path=ModulesCollection}"* >

                </ComboBox>

            </Grid>
        </DataTemplate>

以及背后的视图模型代码。

public class ModulesViewModel :DependencyObject
{
    public ModulesViewModel()
    {
        using(var context =new SPIS_Entities())
        {
            ModulesCollection = context.Module.Where(p => p.active).ToList();
        }
    }

    public List<Module> ModulesCollection
    {
        get
        {
            return (List<Module>)GetValue(ModulesCollectionProperty);
        }
        set 
        { 
            SetValue(ModulesCollectionProperty, value); 
        }
    }

    public static readonly DependencyProperty ModulesCollectionProperty =
                        DependencyProperty.Register("ModulesCollection",
                                                    typeof(List<Module>),
                                                    typeof(ModulesViewModel),
                                                    null);
}

我正在关注互联网上的一些示例,但我一直遇到无法找到“viewModel”ViewModel 的问题。它设置为

视图模型的 XAML 定义设置为用户控件的根。无论我把它放在哪里,它都带有下划线和空值,在鼠标悬停时说“无法创建实例......”。如果我把它放在组合框标签内,它仍然是空的,但没有下划线

建议?

4

1 回答 1

0

在我的解决方案中,我有一个非常简单的代码线。我为我的外键值添加了一个 ListProperty,并在我的业务类的 loadData() 方法中填充了这个列表。

        private void LoadData(ef.table data)
    {
        // method to set all the properties
        //this.example = data.example;
        LoadProperty<ForeignKeyClass>(ForeignKeyProperty, ForeignKeyClass.Get(data.efForeignKeyTable));
    }

    //Property
    public static readonly PropertyInfo<ForeignKeyClass> ForeignKeyProperty = RegisterProperty<ForeignKeyClass>(c => c.ForeignKeyPropertyName);
    public ForeignKeyClass ForeignKeyPropertyName
    {
        get { return GetProperty<ForeignKeyClass>(ForeignKeyProperty); }
        private set
        {
            SetProperty<ForeignKeyClass>(ForeignKeyProperty, value);
        }
    }

现在你有一个属性,它在你的模型中填充了外键数据。不知道这是否对您有所帮助,但是,这就是我将外键数据输入模型的方式。祝你好运

于 2013-06-14T11:27:09.733 回答