WPF ViewModel 获取选中 RadioButton 的 Content 值
在 WPF 中,我们可以使用 RadioButton 控件的 Content 属性来设置按钮的文本内容。如果想要在 ViewModel 中获取选中的 RadioButton 的 Content 值,可以使用以下方法:
- 在 ViewModel 中定义一个属性来保存选中的 RadioButton 的 Content 值
private string _selectedRadioButtonContent;
public string SelectedRadioButtonContent
{
get { return _selectedRadioButtonContent; }
set
{
_selectedRadioButtonContent = value;
OnPropertyChanged(nameof(SelectedRadioButtonContent));
}
}
- 在 View 中为每个 RadioButton 控件绑定 IsChecked 和 Content 属性,并使用一个公共的属性来存储选中的 RadioButton 的 Content 值
<RadioButton Content='Option 1' IsChecked='{Binding IsOption1Checked}' />
<RadioButton Content='Option 2' IsChecked='{Binding IsOption2Checked}' />
<RadioButton Content='Option 3' IsChecked='{Binding IsOption3Checked}' />
// ViewModel 中的属性
public bool IsOption1Checked
{
get { return _isOption1Checked; }
set
{
_isOption1Checked = value;
if (value)
SelectedRadioButtonContent = 'Option 1';
}
}
public bool IsOption2Checked
{
get { return _isOption2Checked; }
set
{
_isOption2Checked = value;
if (value)
SelectedRadioButtonContent = 'Option 2';
}
}
public bool IsOption3Checked
{
get { return _isOption3Checked; }
set
{
_isOption3Checked = value;
if (value)
SelectedRadioButtonContent = 'Option 3';
}
}
- 在 ViewModel 中处理选中的 RadioButton 的 Content 值
private void HandleSelectedRadioButtonContent()
{
switch (SelectedRadioButtonContent)
{
case 'Option 1':
// 处理选中 Option 1 的情况
break;
case 'Option 2':
// 处理选中 Option 2 的情况
break;
case 'Option 3':
// 处理选中 Option 3 的情况
break;
default:
break;
}
}
AI 优化版
原文地址:https://www.cveoy.top/t/topic/mTyT 著作权归作者所有。请勿转载和采集!