WPF单选按钮 - MVVM - 绑定似乎死了?

And*_*rke 7 .net wpf binding mvvm radio-button

DataContext将以下Window 绑定到后面的代码,给我一个MVVM style来演示这种行为:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <StackPanel>
        <RadioButton GroupName="test" Content="Monkey" IsChecked="{Binding IsMonkey}"/>
        <RadioButton GroupName="test" Content="Turtle" IsChecked="{Binding IsTurtle}" />
    </StackPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)

下面是代码背后的代码:

public partial class Window1
{
    public Window1()
    {
        InitializeComponent();
    }

    private bool _isMonkey;
    public bool IsMonkey
    {
        get { return _isMonkey; }
        set
        {
            _isMonkey = value;
        }
    }

    private bool _isTurtle;
    public bool IsTurtle
    {
        get { return _isTurtle; }
        set
        {
            _isTurtle = value;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

把一个断点上的一组IsMonkeyIsTurtle,然后运行该应用程序并选择IsMonkeyIsTurtle后对方我发现,它为每个控件的第一选择,第二选择绑定符和断点不再触发?

有人能指出我正确的方向吗?

HCL*_*HCL 10

您的示例没有更改通知.你写的只是MVVM风格结构的一个例子.因此,我假设您已实现INotifyPropertyChanged或属性为DependencyProperties.如果没有,你要做的第一件事就是改变通知.

如果您有更改通知,请为RadioButtons指定不同的组名(每个实例的另一个名称).这将它们分离,并且绑定将不再被破坏.

<StackPanel> 
    <RadioButton GroupName="test1" Content="Monkey" IsChecked="{Binding IsMonkey}"/> 
    <RadioButton GroupName="test2" Content="Turtle" IsChecked="{Binding IsTurtle}" /> 
</StackPanel> 
Run Code Online (Sandbox Code Playgroud)

根据您的属性的声明,声明Binding TwoWay也可能是有意义的.

IsChecked="{Binding IsMonkey,Mode=TwoWay}
Run Code Online (Sandbox Code Playgroud)

希望这有帮助.