从代码中设置单选按钮
本文关键字:单选按钮 设置 代码 | 更新日期: 2023-09-27 18:17:10
我有一个WPF GUI,正在从磁盘加载记录。当我加载它们时,我需要根据加载的值设置一个单选按钮。
我知道这很容易,但我根本无法让它工作-有人知道所需的代码吗?
按钮在这里:
<RadioButton GroupName="Membership" Content="Probationary" Height="16" HorizontalAlignment="Left" Margin="106,194,0,0" Name="RProbationary" VerticalAlignment="Top" IsChecked="True" Checked="RProbationary_Checked" />
<RadioButton GroupName="Membership" Content="Full" Height="16" HorizontalAlignment="Right" Margin="0,195,90,0" Name="RFull" VerticalAlignment="Top" Checked="RFull_Checked" DataContext="{Binding}" />
设置它们的代码如下:
private void Window_Initialized(object sender, EventArgs e)
{
if (_name.Length != 0)
{
// blah blah lots of awesome code
// here is where we have the required value as a string which needs to be reflected
// on the GUI as a checked radio button
}
}
这样修改你的xaml:
<RadioButton GroupName="Membership" Content="Probationary" Height="16" HorizontalAlignment="Left" Name="RProbationary" VerticalAlignment="Top" IsChecked="True" />
<RadioButton GroupName="Membership" Content="Full" Height="16" HorizontalAlignment="Right" Name="RFull" VerticalAlignment="Top" IsChecked="{Binding RFull_Checked}" />
像这样修改你的c#代码:
public bool RFull_Checked
{
get { return (bool)GetValue(RFull_CheckedProperty); }
set { SetValue(RFull_CheckedProperty, value); }
}
// Using a DependencyProperty as the backing store for RFull_Checked. This enables animation, styling, binding, etc...
public static readonly DependencyProperty RFull_CheckedProperty =
DependencyProperty.Register("RFull_Checked", typeof(bool), typeof(MainWindow), new PropertyMetadata(false));
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
string _name = "bla";
private void Window_Initialized(object sender, EventArgs e)
{
if (_name.Length != 0)
{
RFull_Checked = true;
}
}