WPF 单选按钮 - MVVM - 绑定似乎死了? [英] WPF radio buttons - MVVM - binding seems to die?

查看:43
本文介绍了WPF 单选按钮 - MVVM - 绑定似乎死了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将以下窗口的 DataContext 绑定到后面的代码,以给我一个 MVVM style 来演示此行为:

I've bound the DataContext of the following Window to the code behind to give me a MVVM style to demonstrate this behaviour:

<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 一个接一个地,我发现它适用于每个控件的第一次选择,在第二次选择时绑定中断并且不再触发断点?

Putting a breakpoint on the set of IsMonkey and IsTurtle and then running the application and selecting IsMonkey and IsTurtle after each other I found that it works for the first selection of each control, on the second selection the binding breaks and the breakpoints are no longer triggered?

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

Can anyone point me in the right direction, please?

推荐答案

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

Your example has no Changed-notification. Your wrote it's only an example for an MVVM-style construction. Therefore I assume, you have implemented INotifyPropertyChanged or the properties are DependencyProperties. If not, the first thing you have to do is change-notification.

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

If you have change-notification, give the RadioButtons different group names (another name for each instance). This decouples them and the binding will not be broken anymore.

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

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

Depending on the declaration of your properties, it may also be meaningfull to declare the Binding TwoWay.

IsChecked="{Binding IsMonkey,Mode=TwoWay}

希望这会有所帮助.

这篇关于WPF 单选按钮 - MVVM - 绑定似乎死了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆