Visual Studio 不显示具有 DesignInstance 属性的设计时数据。我已经检查了使用/不使用 MVVM Light 的 DesignInstance
。我花了很多时间来解决这个问题(也在 StackOverflow 上检查了类似的问题)但是 DesignInstance
根本不起作用。
项目:
SearchIdView
。SearchIdViewModel
- 真实 View 模型。DesignSearchIdViewModel
- 继承自SearchIdViewModel
并包含设计时数据(属性在构造函数中分配)。
环境:
- VS2013 SP3
- 网络 4.0
- MvvmLight 5.0.2.0
SearchIdView.xaml
<Window x:Class="App1.View.SearchIdView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ignore="http://www.ignore.com"
xmlns:design="clr-namespace:App1.Design"
mc:Ignorable="d ignore"
DataContext="{Binding SearchId, Source={StaticResource Locator}}"
d:DataContext="{d:DesignInstance d:Type=design:DesignSearchIdViewModel,IsDesignTimeCreatable=True}"
>
<Grid>
<TextBlock Text="{Binding Test}" />
</Grid>
SearchIdViewModel.cs
来自 SearchIdViewModel
的属性
public const string TestPropertyName = "Test";
private string _test;
public string Test
{
get
{
return _test;
}
set
{
Set(TestPropertyName, ref _test, value);
}
}
您知道为什么 DesignInstance
在这种情况下不起作用吗?
解决方法
- 从 View 中删除
d:DataContext
- 添加接口(interface)
ISearchIdViewModel
(它是空的) SearchIdViewModel
继承自ISearchIdViewModel
- 更改
ViewModelLocator
(下)
ViewModelLocator.cs
public class ViewModelLocator
{
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (ViewModelBase.IsInDesignModeStatic)
{
SimpleIoc.Default.Register<ISearchIdViewModel,Design.DesignSearchIdViewModel>();
}
else
{
SimpleIoc.Default.Register<ISearchIdViewModel, SearchIdViewModel>();
}
}
public SearchIdViewModel SearchId
{
get { return (SearchIdViewModel) ServiceLocator.Current.GetInstance<ISearchIdViewModel>(); }
}
}
最佳答案
您的 d:DesignInstance
声明格式不正确。您指定属性名称 d:Type
而不是 Type
,因此未正确分配属性。将 d:Type
替换为 Type
,或者完全保留属性名称并将其推断为默认属性。
d:DataContext="{d:DesignInstance d:Type=design:DesignSearchIdViewModel,
IsDesignTimeCreatable=True}"
应该变成:
d:DataContext="{d:DesignInstance Type=design:DesignSearchIdViewModel,
IsDesignTimeCreatable=True}"
或者,或者:
d:DataContext="{d:DesignInstance design:DesignSearchIdViewModel,
IsDesignTimeCreatable=True}"
(为了便于阅读而添加了换行)
关于c# - DesignInstance 在 VS2013 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26711510/