C#MVVM:将RadioButton绑定到布尔属性

时间:2016-05-28 15:31:10

标签: c# wpf mvvm data-binding radio-button

我对编程很安静,目前正在学习C#和MVVM模式。

我需要为ChiliPlants大学编写数据库工具。 在那里你应该能够向ObservableCollection添加一个新对象。

要向此ObservableCollection添加新项目,将打开一个新窗口。它看起来像这样: Window Add

我现在想要将两个RadioBox绑定到名为“HybridSeed”的属性。这是在ViewModel中定义的:

//Public Property HybridSeed
    public bool HybridSeed
    {
        get { return ChiliModel.HybridSeed; }
        set
        {
            if (ChiliModel.HybridSeed == value)
                return;
            ChiliModel.HybridSeed = value;
            OnPropertyChanged("HybridSeed");
        }
    }

我的View中的RadioBox部分如下所示:

 <RadioButton Grid.Row="5" Content="Ja" Grid.Column="1" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top"/>
    <RadioButton Grid.Row="5" Content="Nein" Grid.Column="1" HorizontalAlignment="Left" Margin="89,10,0,0" VerticalAlignment="Top"/>

但是如何将点击这些RadioButtons的用户的结果绑定到此HybridSeed属性?重要的是结果是一个布尔。

我几乎查找了与此主题相似的每个条目,但我找不到简单的解决方案。或者我能用我糟糕的编码技巧理解的解决方案:( ...

如果你们能帮助我,我会很高兴的。请保持这个新手的简单:)

如果使用CheckBox或ComboBox有更简单的解决方案,它也将是完美的。最重要的是拥有一个不错的用户界面。现在它只适用于TextBox,用户总是必须写“True”或“False”。

解决方案:

我在“Yes”RadioButton中添加了IsClicked属性,以便绑定到我的boulean属性:IsClicked =“{Binding HybridSeed}”。感谢naslund快速回答:)

1 个答案:

答案 0 :(得分:5)

将HybridSeed绑定到Yes-radiobutton。然后,如果用户选择了该值,则为真;如果已选择No-radiobutton(或者如果未选择任何内容),则为假。在这种情况下绑定到两个按钮有点多余,因为radiobutton的机制负责处理它。

WPF:

<RadioButton Content="Yes" IsChecked="{Binding HybridSeed}" />
<RadioButton Content="No" />
<Label Content="{Binding HybridSeed}" ContentStringFormat="Value is: {0}" />

逻辑:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel();
    }
}

public class ViewModel : INotifyPropertyChanged
{
    private bool hybridSeed;

    public bool HybridSeed
    {
        get { return hybridSeed; }
        set
        {
            hybridSeed = value;
            OnPropertyChanged(nameof(HybridSeed));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
相关问题