WPF ViewModels如何获取RadioButton 给Content赋的值
在WPF中,可以通过命名和绑定来获取RadioButton给Content赋的值。
命名方式:
在XAML中为RadioButton命名,例如:
<RadioButton x:Name="RadioButton1" Content="Option 1" />
<RadioButton x:Name="RadioButton2" Content="Option 2" />
然后在ViewModel中通过以下方式获取选中的RadioButton的值:
if (RadioButton1.IsChecked == true)
{
// Option 1 is selected
}
else if (RadioButton2.IsChecked == true)
{
// Option 2 is selected
}
绑定方式:
在XAML中使用绑定将RadioButton的值绑定到ViewModel属性,例如:
<RadioButton Content="Option 1" IsChecked="{Binding Option1IsSelected}" />
<RadioButton Content="Option 2" IsChecked="{Binding Option2IsSelected}" />
然后在ViewModel中定义属性:
private bool _option1IsSelected;
public bool Option1IsSelected
{
get { return _option1IsSelected; }
set
{
if (_option1IsSelected != value)
{
_option1IsSelected = value;
OnPropertyChanged(nameof(Option1IsSelected));
}
}
}
private bool _option2IsSelected;
public bool Option2IsSelected
{
get { return _option2IsSelected; }
set
{
if (_option2IsSelected != value)
{
_option2IsSelected = value;
OnPropertyChanged(nameof(Option2IsSelected));
}
}
}
然后在ViewModel中可以通过Option1IsSelected和Option2IsSelected属性获取RadioButton的值。
原文地址: https://www.cveoy.top/t/topic/bqcm 著作权归作者所有。请勿转载和采集!