.net - WPF 单选按钮 - MVVM - 绑定(bind)似乎死了?

标签 .net wpf mvvm binding radio-button

我绑定(bind)了DataContext下面的窗口到后面的代码给我一个 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>

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

IsMonkey 的集合上设置断点和 IsTurtle然后运行应用程序并选择IsMonkeyIsTurtle在彼此之后,我发现它适用于每个控件的第一次选择,在第二次选择时绑定(bind)中断和断点不再触发?

谁能指出我正确的方向,好吗?

最佳答案

您的示例没有更改通知。您写道,这只是 MVVM 样式构造的一个示例。因此我假设,您已经实现了 INotifyPropertyChanged 或者属性是 DependencyProperties。如果没有,您要做的第一件事就是更改通知。

如果您有更改通知,给 RadioButtons 不同的组名 (每个实例的另一个名称)。这将它们解耦,并且绑定(bind)将不再被破坏。

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

根据您的属性声明,声明 Binding TwoWay 也可能是有意义的。
IsChecked="{Binding IsMonkey,Mode=TwoWay}

希望这有帮助。

关于.net - WPF 单选按钮 - MVVM - 绑定(bind)似乎死了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3750307/

相关文章:

c# - 如何在 try catch 语句中包装 MVVM Light ViewModel?

asp.net-mvc - 使用 MVC 或类似模式时的属性 getter 与获取方法?

c# - 屏幕截图上的窗口没有消失

c# - WPF 子控件,仅样式内容部分

.net - 重写成员时违反了继承安全规则 - SecurityRuleSet.Level2

c# - 接受 "Auto"的 DependencyProperty double 似乎有效但会抛出错误

c# - 在静态类中存储用户信息

mvvm - CommandSink背后的隐喻是什么?

c# - 从 DbCommandDefinition 获取 CommandText

c# - 为什么 List<T>.Enumerator 比我的实现更快?