0

我正在使用一个

public class ObservableDictionary : IObservableMap<string, object>

..在我的 XAML 中绑定到设计时数据。我使用的是在您创建默认 Windows 应用商店应用程序时创建的同一个 ObservableDictionary 类。我的主页使用

public partial class MainPageViewModel : ViewModels.IMainPageViewModel 
{
public ObservableCollection<Models.HubSection> HubSections { get; set; }
public ObservableCollection<ViewModels.IWritingItemViewModel> Writings { get; set; }

private readonly ObservableCollection<Models.ObservableDictionary> defaultDataModel;
public ObservableCollection<Models.ObservableDictionary> DefaultDataModel
{
    get { return this.defaultDataModel; }
}

Models.ObservableDictionary hub = new Models.ObservableDictionary();

public MainPageViewModel()
{
    this.defaultDataModel = new ObservableCollection<Models.ObservableDictionary>();
    this.GetHubSections();
    this.GetWritings();
    this.DefaultDataModel.Add(hub);
}

private void GetHubSections()
{
    var hubSections = DesignTimeData.Factory.GenHubSections();
    this.HubSections = new ObservableCollection<Models.HubSection>();

    foreach (var section in hubSections)
    {
        this.HubSections.Add(section);
    }

    Models.ObservableDictionary hub = new Models.ObservableDictionary();
    hub["HubSections"] = this.HubSections;
}

private void GetWritings()
{
    var writings = DesignTimeData.Factory.GenWritings();
    this.Writings = new ObservableCollection<ViewModels.IWritingItemViewModel>();
    var viewmodels = writings.Select((x, i) => new WritingItemViewModel
    {
        Writing = x,
        VariableItemSize = Common.VariableItemSizes.Normal
    });

    this.Writings.AddRange(viewmodels);
    Models.ObservableDictionary hub = new Models.ObservableDictionary();
    hub["Writings"] = this.Writings;

    if (viewmodels.Any())
    {
        SelWriting = viewmodels.First();
    }
}
}

手动编码的数据来自

public static class Factory
{
public static IEnumerable<Models.HubSection> GenHubSections()
{
    foreach (var hubSection in CreateHubSection())
    {
        yield return hubSection;
    }
}

private static ObservableCollection<Models.HubSection> CreateHubSection()
{
    var writing = new ObservableCollection<Models.HubSection>
    {
#region HubSections

        new Models.HubSection
        {
            UniqueId = "A6C99BE9-3DE5-4625-A763-55623D8CDA55",
            Name = "WritingsHubSection",
            IsHeaderInteractive = false,
            ContentTemplate = "SectionWritingsTemplate",
            HeaderTemplate = "",
            Header = "WRITINGS",
            ImagePath = "ms-appx:///Assets/StoreLogo.scale-180.png",
        },
        new Models.HubSection
        {
            UniqueId = "A6C99BE9-3DE5-4625-A763-55623D8CDA22",
            Name = "SenarioHubSection",
            IsHeaderInteractive = false,
            ContentTemplate = "SectionSenarioTemplate",
            HeaderTemplate = "",
            Header = "SENARIOS",
            ImagePath = "ms-appx:///Assets/StoreLogo.scale-180.png",
        }

#endregion
    };

    return writing;
}
}

在我的 XAML 中,我使用

d:DataContext="{d:DesignInstance designTimeData:MainPageViewModel, IsDesignTimeCreatable=True}">

..用于类的实例化,为我的 MainPage 创建设计时数据

<Grid Background="{ThemeResource AppBackground}"
  d:DataContext="{Binding DefaultDataModel[0]}"
  DataContext="{Binding DefaultDataModel[0]}">
<Hub Margin="0,40,0,0">
    <HubSection MinWidth="{Binding Width, Source={StaticResource WritingsSize}}"
                Header="WRITINGS"
                x:Name="WritingsHubSection">
        <DataTemplate>
            <ListView
                x:Name="itemGridView"
                ItemsSource="{Binding HubSections}"
                Margin="-9,-14,0,0"
                SelectionMode="Single">
                <ListView.ItemTemplate>
                    <DataTemplate >
                        <Grid Height="250" Width="310" Margin="5,10,5,10" Background="Transparent">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto"/>
                                <RowDefinition Height="*"/>
                            </Grid.RowDefinitions>
                            <Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}" Height="150">
                                <Image Source="{Binding ImagePath}" />
                            </Border>
                            <StackPanel Grid.Row="1" Margin="0,10,0,0">
                                <TextBlock Text="{Binding Name}" Style="{StaticResource TitleTextBlockStyle}" TextWrapping="NoWrap"/>
                                <TextBlock Text="{Binding Header}" Style="{StaticResource BodyTextBlockStyle}" MaxHeight="60" />
                            </StackPanel>
                        </Grid>
                    </DataTemplate>

                </ListView.ItemTemplate>

            </ListView>

        </DataTemplate>

    </HubSection>
</Hub>

此代码通常用于在Diederik Krols使用 Windows 8.1 Hub 作为 ItemsControl ”的自定义集线器控件中创建 HubSections,但我无法让它工作,所以我将 XAML 减少到只是一个 ListView 以查看如果我能解决问题。截至目前,当我运行应用程序时,ListView 会显示数据。

但是,当我删除

d:DataContext="{Binding DefaultDataModel[0]}"
DataContext="{Binding DefaultDataModel[0]}"

补充:在阅读了 Luke Pulpit 的“ Windows Store App Design-time DataContext ” 之后,我做了一些改变,因为我们有同样的问题。我添加了 Binding 和 Type 属性,但得到了相同的结果。

为了让这个问题更清楚,我的问题是 ObservableDictionary : IObservableMap 类,为什么我不能绑定到设计时数据的映射。

public class ObservableDictionary : IObservableMap<string, object>
{
private class ObservableDictionaryChangedEventArgs : IMapChangedEventArgs<string>
{
    public ObservableDictionaryChangedEventArgs(CollectionChange change, string key)
    {
        this.CollectionChange = change;
        this.Key = key;
    }

    public CollectionChange CollectionChange { get; private set; }
    public string Key { get; private set; }
}

private Dictionary<string, object> _dictionary = new Dictionary<string, object>();
public event MapChangedEventHandler<string, object> MapChanged;

private void InvokeMapChanged(CollectionChange change, string key)
{
    var eventHandler = MapChanged;
    if (eventHandler != null)
    {
        eventHandler(this, new ObservableDictionaryChangedEventArgs(change, key));
    }
}

public void Add(string key, object value)
{
    this._dictionary.Add(key, value);
    this.InvokeMapChanged(CollectionChange.ItemInserted, key);
}

public void Add(KeyValuePair<string, object> item)
{
    this.Add(item.Key, item.Value);
}

public bool Remove(string key)
{
    if (this._dictionary.Remove(key))
    {
        this.InvokeMapChanged(CollectionChange.ItemRemoved, key);
        return true;
    }
    return false;
}

public bool Remove(KeyValuePair<string, object> item)
{
    object currentValue;
    if (this._dictionary.TryGetValue(item.Key, out currentValue) &&
        Object.Equals(item.Value, currentValue) && this._dictionary.Remove(item.Key))
    {
        this.InvokeMapChanged(CollectionChange.ItemRemoved, item.Key);
        return true;
    }
    return false;
}

public object this[string key]
{
    get
    {
        return this._dictionary[key];
    }
    set
    {
        this._dictionary[key] = value;
        this.InvokeMapChanged(CollectionChange.ItemChanged, key);
    }
}

public void Clear()
{
    var priorKeys = this._dictionary.Keys.ToArray();
    this._dictionary.Clear();
    foreach (var key in priorKeys)
    {
        this.InvokeMapChanged(CollectionChange.ItemRemoved, key);
    }
}

public ICollection<string> Keys
{
    get { return this._dictionary.Keys; }
}

public bool ContainsKey(string key)
{
    return this._dictionary.ContainsKey(key);
}

public bool TryGetValue(string key, out object value)
{
    return this._dictionary.TryGetValue(key, out value);
}

public ICollection<object> Values
{
    get { return this._dictionary.Values; }
}

public bool Contains(KeyValuePair<string, object> item)
{
    return this._dictionary.Contains(item);
}

public int Count
{
    get { return this._dictionary.Count; }
}

public bool IsReadOnly
{
    get { return false; }
}

public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
    return this._dictionary.GetEnumerator();
}

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
    return this._dictionary.GetEnumerator();
}

public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
{
    int arraySize = array.Length;
    foreach (var pair in this._dictionary)
    {
        if (arrayIndex >= arraySize) break;
        array[arrayIndex++] = pair;
    }
}
}

我可以在运行时在代码中执行此操作并获得所需的结果,

var w = this.DefaultDataModel[0];
ObservableCollection<Models.HubSection> hubSections = w["HubSections"] as ObservableCollection<Models.HubSection>;

但当我这样做时不适用于设计时数据:

d:DataContext="{Binding DefaultDataModel[0], Source={d:DesignInstance Type=designTimeData:MainPageViewModel, IsDesignTimeCreatable=True}}"
...
..
ListView x:Name="itemGridView"  ItemsSource="{Binding HubSections}"

它显示数据以及我运行应用程序时的数据,我没有收到任何警告或错误。任何帮助,将不胜感激!

谢谢!...

4

1 回答 1

0

好吧,这不是问题的答案,但在做了更多研究之后,我终于意识到我太技术性了,同时还没有完全理解设计时数据的使用。

它是我真正应该寻找的显示结果,而不是我如何获取数据。

为浪费的帖子道歉!...

于 2015-03-06T20:34:10.857 回答