當我嘗試將窗口的高度和寬度綁定到視圖模型中的屬性時,出現一些問題。這裏有一個小例子來說明問題。這是app.xaml.xs與窗口高度和寬度綁定的問題
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MainWindow mainWindow = new MainWindow();
MainWindowViewModel mainWindowViewModel = new MainWindowViewModel();
mainWindow.DataContext = mainWindowViewModel;
mainWindow.Show();
}
}
這是MainWindow.xaml代碼:
<Window x:Class="TestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="{Binding WindowHeight}"
Width="{Binding WindowWidth}"
BorderThickness="{Binding WindowBorderThickness}">
</Window>
這是視圖模型:
public class MainWindowViewModel
{
public int WindowWidth { get { return 100; } }
public int WindowHeight { get { return 200; } }
public int WindowBorderThickness { get { return 8; } }
}
當節目的開始WindowHeight和WindowBorderThickness(但不是WindowWidth)的getter被調用,所以窗口的高度和邊界被正確設置,但不是寬度。
我再添加按鈕,將觸發的PropertyChanged所有屬性,使視圖模型現在看起來是這樣的:
public class MainWindowViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void TriggerPropertyChanges()
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("WindowWidth"));
PropertyChanged(this, new PropertyChangedEventArgs("WindowHeight"));
PropertyChanged(this, new PropertyChangedEventArgs("WindowBorderThickness"));
}
}
public ICommand ButtonCommand { get { return new RelayCommand(delegate { TriggerPropertyChanges(); }); } }
public int WindowWidth { get { return 100; } }
public int WindowHeight { get { return 200; } }
public int WindowBorderThickness { get { return 8; } }
}
現在,當我按一下按鈕,WindowBorderThickness的吸叫,但不WindowWidth和WindowHeight。這一切似乎很奇怪,對我來說不一致。我錯過了什麼?
您在調試時在輸出窗口中有任何警告嗎? – Drake 2010-04-20 13:59:02
不,沒有警告。 – 2010-04-20 14:12:42