当我尝试将窗口的高度和宽度绑定到视图模型中的属性时,出现一些问题。这里有一个小例子来说明问题。这是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