C# WPF:如何将XAML元素尺寸绑定到ViewModel的int类型值?
问题原因及解决方案
你的绑定不生效的核心问题是:WPF数据绑定仅支持绑定到公共属性,无法直接绑定字段。你ViewModel里的WidthOfBorder和HeightOfBorder是公共字段,不是属性,所以绑定无法识别。
第一步:将字段改为公共属性
修改MainWindowViewModel.cs,把字段改成带getter的属性:
public class MainWindowViewModel { // 改为公共属性,WPF绑定需要访问属性的getter public int WidthOfBorder { get; } public int HeightOfBorder { get; } public MainWindowViewModel() { WidthOfBorder = 200; HeightOfBorder = 100; } }
第二步(可选):支持动态更新值
如果后续你需要修改ViewModel中的宽高值并让UI自动同步,还需要让ViewModel实现INotifyPropertyChanged接口,通过触发通知来更新UI:
using System.ComponentModel; using System.Runtime.CompilerServices; public class MainWindowViewModel : INotifyPropertyChanged { private int _widthOfBorder; private int _heightOfBorder; public int WidthOfBorder { get => _widthOfBorder; set { if (_widthOfBorder != value) { _widthOfBorder = value; OnPropertyChanged(); } } } public int HeightOfBorder { get => _heightOfBorder; set { if (_heightOfBorder != value) { _heightOfBorder = value; OnPropertyChanged(); } } } public MainWindowViewModel() { WidthOfBorder = 200; HeightOfBorder = 100; } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
另外建议调整MainWindow构造函数的执行顺序,先调用InitializeComponent()再设置DataContext,这是更规范的WPF开发写法:
public MainWindow() { InitializeComponent(); MainWindowViewModel viewModel = new MainWindowViewModel(); this.DataContext = viewModel; }
内容的提问来源于stack exchange,提问作者mmdn
相关产品推荐
相关产品推荐

