当我尝试将窗口的高度和宽度绑定到我的视图模型中的属性时,遇到了一些问题。这是一个小的示例应用程序,以说明这个问题。以下是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 的 getter 方法(但不包括 WindowWidth ),这样窗口的高度和边框会正确设置,但宽度不会。
然后我添加了一个按钮,触发所有属性的 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的getter被调用了,但是WindowWidth和WindowHeight的getter却没有被调用。这一切对我来说似乎非常奇怪和不一致。我错过了什么吗?