假设WPF TwoWay数据绑定 Wont 对没有焦点的控件有效是否安全?
例如,在以下代码中。
<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>
当我点击radiobutton Value2时,BindTest1 / Value1的值将保持 true ,因为radiobutton Value1在没有焦点的情况下改变了吗?
这是WPF的正常行为吗?我知道我可以通过使用各种技术来避免这种情况,但我想问这是否正常,或者我的Xaml缺少一些导致此问题的参数。
答案 0 :(得分:1)
绑定将更新,无论控件是否具有焦点。我的猜测是你的XAML还有其他错误。
答案 1 :(得分:1)
最后,我找到了答案。基本上,RadioButtons的绑定会中断,因为每次更改绑定时,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();
}
}