如何在代码中以编程方式实现这一行XAML? (因为我需要动态创建单选按钮,但它们具有绑定功能)
<RadioButton IsChecked="{Binding Path=Mode, Converter={StaticResource enumBooleanConverter}, ConverterParameter=Proxy}">Proxy</RadioButton>
到目前为止,我已经到了这里(见下文),但现在我正在努力解决如何将绑定连接起来。我做了一个猜测/假设我应该使用Binding类...
foreach (KeyValuePair<int, string> @interface in interfaces)
{
// RadioButton IsChecked="{Binding Path=Mode, Converter={StaticResource enumBooleanConverter}, ConverterParameter=Proxy, UpdateSourceTrigger=PropertyChanged , Mode=TwoWay}">Proxy</RadioButton>
// Create Radio Button
var newRb = new RadioButton();
newRb.Name = "I" + @interface.Key.ToString();
newRb.GroupName = "InterfaceGroup";
newRb.Content = @interface.Value;
// Binding
var binding = new Binding();
binding.Source = "Interface";
binding.Converter = new RadioBoolToIntConverter();
binding.ConverterParameter = @interface.Key;
// STUCK HERE - RE HOW TO GET THE BINDING TO BE APPLIED TO THE RADIO BUTTON
InterfacesRadioButtons.Children.Add(newRb);
}
对于后台具有依赖项对象的模型类:
public class ConfigWindowViewModel : DependencyObject
{
// Interface Number
public int Interface
{
get { return (int)GetValue(InterfaceProperty); }
set { SetValue(InterfaceProperty, value); }
}
public static readonly DependencyProperty InterfaceProperty =
DependencyProperty.Register("Interface", typeof(int), typeof(ConfigWindowViewModel), new UIPropertyMetadata(0));
}
答案 0 :(得分:5)
newRb.SetBinding(RadioButton.IsCheckedProperty, binding);
可替换地:
BindingOperations.SetBinding(radioButton, RadioButton.IsCheckedProperty, binding);