代码之家  ›  专栏  ›  技术社区  ›  Andy Clarke

无线按钮-MVVM-绑定似乎死了?

  •  7
  • Andy Clarke  · 技术社区  · 16 年前

    我已经把 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 然后运行应用程序并选择 ismonkey键 和 峡部 在彼此之间我发现它对每个控件的第一个选择有效之后,在第二个选择中,绑定中断和断点不再触发?

    有人能给我指个方向吗?

    3 回复  |  直到 11 年前
        1
  •  10
  •   Heiberg    12 年前

    您的示例没有更改通知。你写的它只是一个MVVM风格构造的例子。因此,我想,你已经实现了 INotifyPropertyChanged 或者属性是DependencyProperties。如果没有,首先要做的就是更改通知。

    如果您有变更通知, 为单选按钮指定不同的组名 (每个实例的另一个名称)。这将使它们分离,绑定将不再被破坏。

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

    根据属性的声明,声明绑定twoway也可能有意义。

    IsChecked="{Binding IsMonkey,Mode=TwoWay}
    

    希望这有帮助。

        2
  •  2
  •   akjoshi HCP    16 年前

    这是wpf单选按钮的已知问题;有关详细信息和解决方法,请查看这些文章。-

    WPF单选按钮和数据绑定: http://geekswithblogs.net/claraoscura/archive/2008/10/17/125901.aspx

    节俭的WPF单选按钮绑定(枚举和错误修复): http://inquisitorjax.blogspot.com/2009/02/wpf-radio-button-binding-enums-and-bug.html

    单选按钮未选中的绑定问题仍然没有解决? http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/8eb8280a-19c4-4502-8260-f74633a9e2f2/

        3
  •  0
  •   karfus    11 年前

    这个问题已经在WPF 4.0中得到了解决,我现在正在自己的项目中利用这个行为。只需将单选按钮放在同一组中,就不再需要使用不同的组名。绑定不会被破坏…事实上,“取消选定”单选按钮的绑定值将如预期的那样设置为false。

    推荐文章