你正試圖做一個非常奇怪的詭計,這不應該工作。嘗試進行以下更改。
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