如何设置在WPF设计模式下显示绑定属性的值?

Nam*_* VU 6 data-binding wpf designmode

我的绑定内容empty在UI设计模式中显示为字符串.我想为这些内容显示一些伪造的值,但我不知道如何.

如果你知道如何,请分享.谢谢!

Fre*_*lad 10

在Visual Studio 2010中获取设计时数据的简单方法是使用design-datacontext.使用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>
Run Code Online (Sandbox Code Playgroud)

在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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这里找到的Designer.cs 看起来像这样

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;
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

您也可以使用FallbackValue属性在设计时显示某些内容.但如果绑定失败,这也将是运行时的值.

<TextBox Text="{Binding MyText, FallbackValue='My Fallback Text'}"/>
Run Code Online (Sandbox Code Playgroud)