wpf - 如何在 WPF 设计模式下设置要显示的绑定(bind)属性的值?

标签 wpf data-binding designmode

我的绑定(bind)内容显示为 empty UI 设计模式中的字符串。我想为这些内容显示一些伪造的值(value),但我不知道该怎么做。

如果你知道怎么做,请分享。谢谢!

最佳答案

在 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;
    }
}

关于wpf - 如何在 WPF 设计模式下设置要显示的绑定(bind)属性的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4314103/

相关文章:

c# - WPF 进度条随着项目列表的运行而更新

wpf - 如何访问位于 ControlTemplate 中的 WPF 控件?

javascript - ng-model 不更新 Controller 值

wpf - C#/WPF 数据绑定(bind)和后台 worker

asp.net - visual studio 2012 在设计模式下显示隐藏标签

javascript - DesignMode 中的浏览器在 UL 中包装孤立 LI 元素 - Firefox 和 Chrome

c# - 如何在 WPF UserControl 中显示动态区域性格式化数字

c# - CollectionView 实时排序回调

c# 组合框绑定(bind)到对象列表

ios - UIWebView 中的 contentEditable/designMode 时自动滚动