2009-10-29 182 views
1

是否可以安全地假設WPF雙向數據綁定不會對不具備焦點的控件起作用?WPF雙向數據綁定限制

例如在下面的代碼中。

<Window.Resources> 
     <XmlDataProvider x:Key="TestBind1" XPath="/BindTest1"> 
      <x:XData> 
       <BindTest1 xmlns=""> 
        <Value1>True</Value1> 
       </BindTest1> 
      </x:XData> 
     </XmlDataProvider> 
    </Window.Resources> 
    <StackPanel> 
     <GroupBox> 
      <StackPanel> 
       <RadioButton Content="Value1" IsChecked="{Binding Source={StaticResource TestBind1},Mode=TwoWay, XPath=Value1}"/> 
       <RadioButton Content="Value2"/> 
      </StackPanel> 
     </GroupBox> 
     <Button Content="Analyse" Click="OnAnalyseClicked"/> 

    </StackPanel> 

當我在單選按鈕點擊值2,BindTest1 /值1的值將保持真正因爲單選按鈕值1改變,而它沒有具有焦點?

這是WPF的正常行爲嗎?我知道我可以通過使用各種技術避免這種情況,但我想問這是否正常,或者是我的Xaml缺少導致此問題的某些參數。

回答

1

最後,我找到了答案。基本上,綁定,因爲每次你改變它的結合將打破單選按鈕,該單選按鈕將

我找到了答案here,這是一家專業的單選按鈕,防止從綁定組中更改其他按鈕的選中狀態正在改變。

我用來修復綁定的示例類。

/// <summary> 
    /// data bound radio button 
    /// </summary> 
    public class DataBoundRadioButton : RadioButton 
    { 
     /// <summary> 
     /// Called when the <see cref="P:System.Windows.Controls.Primitives.ToggleButton.IsChecked"/> property becomes true. 
     /// </summary> 
     /// <param name="e">Provides data for <see cref="T:System.Windows.RoutedEventArgs"/>.</param> 
     protected override void OnChecked(RoutedEventArgs e) 
     { 
      // Do nothing. This will prevent IsChecked from being manually set and overwriting the binding. 
     } 

     /// <summary> 
     /// Called by the <see cref="M:System.Windows.Controls.Primitives.ToggleButton.OnClick"/> method to implement a <see cref="T:System.Windows.Controls.RadioButton"/> control's toggle behavior. 
     /// </summary> 
     protected override void OnToggle() 
     { 
      BindingExpression be = GetBindingExpression(RadioButton.IsCheckedProperty); 
      Binding bind = be.ParentBinding; 

      Debug.Assert(bind.ConverterParameter != null, "Please enter the desired tag as the ConvertParameter"); 

      XmlDataProvider prov = bind.Source as XmlDataProvider; 
      XmlNode node = prov.Document.SelectSingleNode(bind.XPath); 
      node.InnerText = bind.ConverterParameter.ToString(); 

     } 
    } 
1

綁定更新,無論控件是否有焦點。我的猜測是你的XAML有其他問題。