【发布时间】:2011-02-10 01:02:48
【问题描述】:
当我尝试将窗口的高度和宽度绑定到我的视图模型中的属性时,我遇到了一些问题。这是一个小示例应用程序来说明问题。这是 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 的 getter,但不会调用 WindowWidth 和 WindowHeight 的 getter。这一切对我来说似乎很奇怪和不一致。我错过了什么?
【问题讨论】:
-
调试时输出窗口有警告吗?
标签: c# .net wpf data-binding binding