WPF& MVVM,在Window中设计时间数据,但不是子UserControl

时间:2014-05-25 22:22:14

标签: wpf mvvm

在Visual Studio 2013(完全更新)和Blend 2013中,我没有在UserControl中看到设计时数据,但我在Window中看到了具有UserControl的设计时数据。以下是我的问题的简化演示。

模型( color.cs ):

using System;
namespace TestWPF {
    public class color {
        public string name { get; set; }
    }
}

ModelView( colorViewModel.cs ):

using System;
using System.Collections.Generic;

namespace TestWPF
{
    public class colorViewModel
    {
        public List<color> colorList;
        public colorViewModel()
        {
            colorList = new List<color>();
            colorList.Add(new color() { name = "blue" });
            colorList.Add(new color() { name = "red" });
        }
    }
}

UserControl代码隐藏( colorUserControl.xaml.cs ):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TestWPF
{
    public partial class colorUserControl : UserControl
    {
        public colorUserControl()
        {
            InitializeComponent();
            this.DataContext = (new colorViewModel()).colorList;
        }
    }
}

UserControl XAML( colorUserControl.xaml ):

<UserControl x:Class="TestWPF.colorUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <DataGrid ItemsSource="{Binding}" AutoGenerateColumns="True" />
    </Grid>
</UserControl>

Window XAML( MainWindow.xaml ):

<Window x:Class="TestWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        xmlns:view="clr-namespace:TestWPF">
    <Grid>
        <view:colorUserControl />
    </Grid>
</Window>

窗口获取设计时数据:

enter image description here

但不是UserControl:

enter image description here

如何让我的UserControl显示设计时间数据?

1 个答案:

答案 0 :(得分:1)

您遇到的问题是您实际上并未使用设计时数据,即使在主窗口中也是如此。


使用设计时数据时,您有两种选择:

  1. DesignInstance - 用于帮助塑造datacontext。它将为您提供关于绑定路径的智能支持。
  2. DesignData - 这将允许您选择一个xaml资源,该资源代表您的datacontext和实际样本数据。
  3. 不幸的是,你必须只选择一个(它们不能共存)。


    下面列出了一些好的资源: