Dot-Net

WPF 單選按鈕 - MVVM - 綁定似乎死了?

  • May 22, 2015

我已將DataContext以下 Window 綁定到後面的程式碼,以給我一個 MVVMstyle來展示此行為:

<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然後執行應用程序並選擇IsMonkey,然後IsTurtle我發現它適用於每個控制項的第一次選擇,在第二次選擇時綁定中斷並且斷點不再被觸發?

誰能指出我正確的方向,好嗎?

您的範例沒有更改通知。您寫道,這只是 MVVM 樣式構造的一個範例。因此我假設,您已經實現INotifyPropertyChanged或屬性是 DependencyProperties。如果沒有,您要做的第一件事就是更改通知。

如果您有更改通知,請給 RadioButtons 不同的組名(每個實例的另一個名稱)。這將它們解耦,並且綁定將不再被破壞。

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

希望這有幫助。

引用自:https://stackoverflow.com/questions/3750307