How to display placeholder value in WPF Visual Studio Designer until real value can be loaded

大憨熊 提交于 2019-12-06 18:21:48

问题


I'm an experienced C# developer but a WPF newbie. Basic question (I think) that I can't find an answer to by web searching. Here's the simplified use case...

I want to display a string in a WPF TextBlock. So I write some C# code in codebehind of my XAML control...

public class MyCoolControl : UserControl
{
   public void InitializeMyCoolControl()
   {
      this.DataContext = "SomeStringOnlyAvailableAtRuntime"; // Perhaps from a database or something...
   }
}

And I set up my XAML like this:

<UserControl ... snip...>
   <!-- Bind the textblock to whatever's in the DataContext -->
   <TextBlock Text="{Binding}"></TextBlock>
</UserControl>

Works great, I can see the value "SomeStringOnlyAvailableAtRuntime" when I execute my application. However, I don't see anything at Design Time using Visual Studio 2008's XAML Designer.

How can I see a placeholder value (anything) for the textblock at design time?

Thanks!

-Mike


回答1:


I often use FallbackValue on the binding to have something to look at while I design user controls. For example:

<TextBlock Text={Binding Path=AverageValue, FallbackValue=99.99} />

However, since FallbackValue is not just applied at design time, this might not be appropriate if you want to use FallbackValue at run time for other reasons.




回答2:


In your example you might need to use TargetNullValue, not FallbackValue as the binding expression is likely to be null as the DataContext is null at design time.

FallBackValue is used if the Path given in the binding does not exist, but as no path is specified I'd assume the DataContext would then be evaluated as null.

<UserControl ... snip...>
  <!-- Bind the textblock to whatever's in the DataContext -->   
    <TextBlock Text="{Binding TargetNullValue=Nothing to see}"></TextBlock>
</UserControl>

Also note that .NET Framework 3.5 SP1 is needed as these two additional properties were added in SP1.




回答3:


I don't know of a way to do this with Visual Studio's editor, but you can do this with Expression Blend.

Here's and article describing how to achieve this.

I do hope that MS merge the functionality of Blend and Visual Studio together because having one package do one thing and another something else is a bit silly. Especially when they're from the same company.




回答4:


Isn't the best option in this scenario to have a MultiValueConverter or ViewModel object handle the object load and update a dependency property for you?



来源:https://stackoverflow.com/questions/695263/how-to-display-placeholder-value-in-wpf-visual-studio-designer-until-real-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!