【问题标题】:WPF TwoWay data binding limitationWPF TwoWay 数据绑定限制
【发布时间】:2009-10-29 04:07:03
【问题描述】:

假设 WPF TwoWay 数据绑定不会在没有焦点的控件上工作是否安全?

例如在下面的代码中。

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

当我点击单选按钮 Value2 时,BindTest1/Value1 的值将保持 true,因为单选按钮 Value1 在没有焦点的情况下发生了变化?

这是 WPF 的正常行为吗?我知道我可以通过使用各种技术来避免这种情况,但我想问一下这是否正常,或者我的 Xaml 是否缺少导致此问题的某些参数。

【问题讨论】:

    标签: c# wpf data-binding


    【解决方案1】:

    绑定更新,无论控件是否具有焦点。我的猜测是您的 XAML 中还有其他问题。

    【讨论】:

      【解决方案2】:

      终于,我找到了答案。基本上,RadioButtons 的绑定会中断,因为每次您更改其绑定时,单选按钮都会更改组中其他按钮的选中状态

      我找到了答案here,它是专门化 RadioButton 并防止绑定被更改。

      我用来修复绑定的示例类。

       /// <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();
      
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2012-05-12
        • 2023-04-10
        • 2011-08-06
        • 2013-04-12
        • 1970-01-01
        • 2015-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多