2009-10-29 142 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有其他问题。