你正试图做一个非常奇怪的诡计,这不应该工作。尝试进行以下更改。
MainWindow.xaml.cs - 尽量让你的代码保持清晰。
namespace WpfTryIt
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
MainWindow.xaml
<Window x:Class="WpfTryIt.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
xmlns:s ="clr-namespace:WpfTryIt"
>
<Window.DataContext>
<s:FakeDataContext></s:FakeDataContext>
</Window.DataContext>
<Button Content="{Binding Path=BindingHeight}"/>
</Window>
和一个新的独立的数据上下文类,根据不同的模式,它表现出不同:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows;
namespace WpfTryIt
{
public class FakeDataContext
{
public int BindingHeight
{
get
{
// Check for design mode.
if ((bool)(DesignerProperties.IsInDesignModeProperty.GetMetadata(typeof(DependencyObject)).DefaultValue))
{
//in Design mode
return 100;
}
else
{
return 200;
}
}
}
}
}
万一FakeDataContext的构造需要一些论据,我怎样才能修改你的代码,使其工作? – 2010-10-22 10:54:42
我也更新了我的问题,解释为什么我尝试'奇怪的技巧'。 – 2010-10-22 11:30:50
@Nam Gi VU:在XAML中,只能创建具有空构造函数的对象。如果你仍然想用参数实例化一个对象,看看这个问题http://stackoverflow.com/questions/2335900/using-xamlreader-for-controls-that-does-not-have-a-default-constructor – 2010-10-22 12:10:41