在 WPF MVVM 中,可以使用绑定来获取 RadioButton 的值。

首先,在 ViewModel 中定义一个属性来存储 RadioButton 的值:

private bool _isMale;
public bool IsMale
{
    get { return _isMale; }
    set { _isMale = value; OnPropertyChanged(nameof(IsMale)); }
}

然后,在 View 中,使用 RadioButton 的 IsChecked 属性绑定到 ViewModel 的 IsMale 属性:

<RadioButton Content='Male' IsChecked='{Binding IsMale, Mode=TwoWay}' />
<RadioButton Content='Female' IsChecked='{Binding IsMale, Converter={StaticResource InverseBooleanConverter}, Mode=TwoWay}' />

这里使用了一个 InverseBooleanConverter,将 IsMale 的值从 true/false 转换为 false/true。

最后,在 ViewModel 中实现 INotifyPropertyChanged 接口,以便当 RadioButton 的值发生变化时,能够通知 View 更新:

public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
WPF MVVM 获取 RadioButton 值的最佳实践

原文地址: https://www.cveoy.top/t/topic/mR5f 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录