【发布时间】:2010-11-30 13:09:57
【问题描述】:
我的绑定内容在 UI 设计模式中显示为empty 字符串。我想为这些内容显示一些伪造的值,但我不知道该怎么做。
如果你知道怎么做,请分享。谢谢!
【问题讨论】:
标签: wpf data-binding designmode
我的绑定内容在 UI 设计模式中显示为empty 字符串。我想为这些内容显示一些伪造的值,但我不知道该怎么做。
如果你知道怎么做,请分享。谢谢!
【问题讨论】:
标签: wpf data-binding designmode
在 Visual Studio 2010 中获取设计时数据的一种简单方法是使用设计数据上下文。带有 Window 和 ViewModel 的简短示例,对于 DataContext,d:DataContext 将在设计模式下使用,StaticResource 将在运行时使用。您也可以使用单独的 ViewModel 进行设计,但在此示例中,我将为两者使用相同的 ViewModel。
<Window ...
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:DesignTimeData"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance local:MyViewModel,
IsDesignTimeCreatable=True}">
<Window.Resources>
<local:MyViewModel x:Key="MyViewModel" />
</Window.Resources>
<Window.DataContext>
<StaticResource ResourceKey="MyViewModel"/>
</Window.DataContext>
<StackPanel>
<TextBox Text="{Binding MyText}"
Width="75"
Height="25"
Margin="6"/>
</StackPanel>
</Window>
在 ViewModels 属性 MyText 中,我们检查是否处于设计模式,在这种情况下,我们会返回其他内容。
public class MyViewModel : INotifyPropertyChanged
{
public MyViewModel()
{
MyText = "Runtime-Text";
}
private string m_myText;
public string MyText
{
get
{
// Or you can use
// DesignerProperties.GetIsInDesignMode(this)
if (Designer.IsDesignMode)
{
return "Design-Text";
}
return m_myText;
}
set
{
m_myText = value;
OnPropertyChanged("MyText");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Designer.cs,找到here,长这样
public static class Designer
{
private static readonly bool isDesignMode;
public static bool IsDesignMode
{
get { return isDesignMode; }
}
static Designer()
{
DependencyProperty prop =
DesignerProperties.IsInDesignModeProperty;
isDesignMode =
(bool)DependencyPropertyDescriptor.
FromProperty(prop, typeof(FrameworkElement))
.Metadata.DefaultValue;
}
}
【讨论】:
您也可以使用 FallbackValue 属性在设计时显示某些内容。但是,如果您的绑定失败,这也将是运行时的值。
<TextBox Text="{Binding MyText, FallbackValue='My Fallback Text'}"/>
【讨论】:
您可以使用 DesignMode 属性来确定您是否处于设计阶段 (http://msdn.microsoft.com/en-us/library/c58hb4bw(vs.71).aspx)
在这个问题上有进一步的想法,但没有关于如何做到这一点的真正结论:What approaches are available to dummy design-time data in WPF?
【讨论】:
您可以将您的内容包装在另一个属性中并测试该值是否为空。在这种情况下,返回你想要的假值。
private string _content;
public string Content
{
get
{
if (_content != "") return _content;
else return "FAKE";
}
set { _content= value; }
}
【讨论】:
Content 属性不能具有string.Empty 值,不是吗(在设计模式和运行时)?如果是,那不是我要找的(仅设计模式值)