简体   繁体   中英

Visual Studio 2013 WPF design-time data isn't displayed

i have some UserControls that are shown fine in designer, but i can't make any changes to the design-time example content from the constructor. It seems like it is not executed at all.

XAML:

<UserControl x:Class="Example.Test"
         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>
        <TextBlock Name="testx" Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Center"></TextBlock>
</Grid>

Code:

using System.ComponentModel;
using System.Windows.Controls;

namespace Example
{
    /// <summary>
    /// Interaction logic for Test.xaml
    /// </summary>
    public partial class Test : UserControl
    {
        public Test()
        {
            InitializeComponent();
            if (DesignerProperties.GetIsInDesignMode(this))
                testx.Text = " IN DESIGN!";
        }
    }
}

I've tried many options, but still can't get it how to display design-time data in WPF designer :( Different context binding also shows nothing...

PS: Tried clean VS2012 and VS2013 projects on Win8. NOTHING WORKS! :( I don't know what to do, haven't found anything similar on the net... Is it sufficient to just add design check in constructor and set existent control text? It should work, right?

K, the short answer is: You're on the right path.
The long one is: It's a bit more complicated than that.

Your example will "kinda" work, as in, if you'll put an else testx.Text = RUNTIME; after your if , like that:

if (DesignerProperties.GetIsInDesignMode(this))
   testx.Text= " IN DESIGN!";
else
   testx.Text= " Runtime";

you'll see what you want on runtime , but you're design time will stay empty.

For the Design time, you also need to set the context if I'm not mistaken. If you're using any of the MVVM framework out there, you kinda get this functionality for "free". As in, you'll have a "in design time" property and you can set whatever data you want for the design. The catch is that you need to have an empty constructor if my memory serves me right. You'll also use bindings, and not set the text property directly.

I remember that the default WPF and binding for design time was lacking a bit last time I tried to do something like that in "vanilla" wpf (as in, no MVVM, no bindings), but I believe that with a bit of a hack it's achievable. Again, can't remember it from the top of my head.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM