WPF TwoWay data binding limitation
Is it safe to assume that WPF TwoWay data binding Wont开发者_StackOverflow中文版 work on controls which dont have focus ?
For example in the following code.
<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>
When i click on the radiobutton Value2, the value of BindTest1/Value1 will remain true because radiobutton Value1 changed whilst it didnt have focus ?
Is this normal behaviour for WPF ? I am aware that i can avoid this by using various techniques, but i wanted to ask if this is normal or is my Xaml missing some parameter causing this problem.
Bindings will update regardless of whether or not controls have focus. My guess is that something else is wrong in your XAML.
Finally , i found an answer. Basically, the binding will break for RadioButtons because everytime you change its binding, the radiobuttons will change the checked state of other buttons in the group
I found the answer here, which is specialize the RadioButton and prevent the binding from being changed.
Sample class which i used to fix the binding.
/// <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();
}
}
精彩评论