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

7

我已将以下窗口的DataContext绑定到代码后面,以便为我提供MVVM样式来演示此行为:

<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>

这是后面的代码:
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;
        }
    }
}

将断点放在 IsMonkeyIsTurtle 上,运行应用程序并依次选择 IsMonkeyIsTurtle 后,我发现它对每个控件的第一次选择有效,在第二次选择时绑定会中断,断点不再触发。请问有人能指点一下吗?
3个回答

11

你的示例中没有更改通知。你写的只是MVVM构造的示例。因此我假设你已经实现了INotifyPropertyChanged或者这些属性是DependencyProperties。如果没有,那么你需要做的第一件事就是增加更改通知。

如果你已经有了更改通知,请给单选按钮分配不同的组名称(每个实例都使用另一个名称)。这样可以将它们解耦,而绑定就不会再被破坏了。

<StackPanel> 
    <RadioButton GroupName="test1" Content="Monkey" IsChecked="{Binding IsMonkey}"/> 
    <RadioButton GroupName="test2" Content="Turtle" IsChecked="{Binding IsTurtle}" /> 
</StackPanel> 

根据你属性的声明方式,声明双向绑定可能也是有意义的。

IsChecked="{Binding IsMonkey,Mode=TwoWay}
希望这能有所帮助。

嗨,谢谢 - 我按照你建议的使用不同的组名和一些属性代码使它工作了。虽然这很烦人,因为它是相同的组 - 所以我想使用那个功能,但它不让我这样做。 - Andy Clarke
1
给单选按钮分配不同的组名称。我的天啊,你救了我一命。 - user1112008

2

0
这个问题在WPF 4.0中已经修复了,我现在正在我的项目中利用这个行为。只需将单选按钮放入同一组中,就不再需要使用不同的组名了。绑定将不会被破坏...事实上,“取消选择”的单选按钮将按预期将其绑定值设置为false。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接