如何引用在运行时从数据库生成的XAML StaticResource?

时间:2019-03-06 17:32:05

标签: c# wpf xaml staticresource

我有一些枚举列表,我将它们维护为一系列数据库表,我想映射到XAML中的ComboBoxes。在应用程序启动时,我将其创建为StaticResources,如下所示:

            string[] enum_list = 
            {
                // Anything in this list maps to a database table name that starts with "enum_"
                "systemmode",
                [...]
            };

        var dictionary = new ResourceDictionary();
        foreach (string enumstring in enum_list)
        {
            string query = String.Format("SELECT `key` AS A, value AS B FROM enum_{0} ORDER BY A", enumstring);
            Dictionary<int, string> enumDict = db.Database.SqlQuery<QueryResultIntKey>(query)
                                            .ToDictionary(r => r.A, r => r.B);
            dictionary.Add(key: "enum_"+enumstring, value: enumDict);
        }

        this.Resources = dictionary;

我在数据绑定组合框中使用以下内容进行引用:

            <ComboBox x:Name="cmb_SystemMode"
                  Grid.Row="3"
                  Grid.Column="1"
                  ItemsSource="{StaticResource enum_systemmode}"
                  DisplayMemberPath="Value"
                  SelectedValuePath="Key"
                  SelectedValue="{Binding Rset.Recipe.SystemMode, Mode=TwoWay, Converter={StaticResource longconverter}}" />

标记为ItemsSource ...的行在设计器中以蓝色波浪形显示。我理解为什么,因为我生成了这些StaticResources,并在运行时将它们放置在ResourceDictionary中。

我可以运行它,一切都可以解决,并且在运行时非常高兴。

此ComboBox包含在UserControl中。除了蓝色的波浪状和一些抱怨它无法解决的问题,设计师还会允许我 打开用户控件。

但是,当我打开包含UserControl的MainWindow时,XAML解析器会抛出一个错误并拒绝加载UserControl,因为它无法解析StaticResource的名称。

是否有某种方法可以在启动时使用db查询动态生成组合框列表,而不会在Designer中破坏XAML解析器?我尝试在XAML参考中用DynamicResource替换StaticResource,但这不能解决问题。

0 个答案:

没有答案
相关问题