开发者

How to supply a design time value for silverlight textblock that is bound to viewmodel property?

I have a TextBlock in my XAML that has its text bound to a property in my viewmodel.

<TextBlock x:Name="SomeText" Text="{Binding TheTex开发者_高级运维tProperty}" />

This works fine, but at design time, there is no viewmodel so the property is unresolvable and the text is blank. This is hard to work with in the designer because it shows no visible text.

How can I specify some default text to use at design time?


Maybe you could try

<TextBlock x:Name="SomeText" Text="{Binding TheTextProperty, FallbackValue='Some other text'}" />

as documented here.


You can also use Design Time Data to provide a rich binding experience in your solution. Its a little hard to set up and get running, but here's the gist.

First, you create your DataContext in xaml. Add a new Xml document to your solution (the root is a good place) and give it an .xaml extension. Lets call this file "foo.xaml" for this example.

In this file, remove all of the XML and start creating an instance of your DataContext type. For example, if your DataContext was a string (very simple example) your file would look like the following:

<string xmlns="clr-namespace:System;assembly=mscorlib">LOL!</string>

You might have yours look like

<ViewModel xmlns="clr-namespace:MyNamespace">
    <ViewModel.MyObservableCollection>
         <MyModel Name="foo" />
         <!-- etc -->

Set the Build Action on this file to DesignDataWithDesignTimeCreatableTypes:

How to supply a design time value for silverlight textblock that is bound to viewmodel property?

Next, in your View, add the following namespaces and properties to the root of your Window/UserControl:

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DataContext="{d:DesignData Source=foo.xaml}"

Source is relative to the current document. So, if your solution looked like

  • Views
    • MyUserControl.xaml
  • Data
    • foo.xaml

you would set the Source to ../Data/foo.xaml.

There are other ways to create a DesignData context depending on whether your ViewModel can be instantiated at design time, etc.


Another option is to use the DesignerProperties.GetIsInDesignMode function to determine if the control is hosted in VS/Blend and Generate a fake DataContext in that case. Laurent Bugnion provides a number of examples of how to create and use design-time data in this post

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜