WPF binding problem with certain property names
I've stumbled over the following problem. I've got a checkbox whose IsChecked
property is bound to a CLR property in my MainWindow
class. Here's the source code.
Code behind (MainWindow.xaml.cs
):
namespace MenuItemBindingTest {
public partial class MainWindow : Window, INotifyPropertyChanged {
private bool m_backedVariable = false;
public bool IsPressAndHoldEnabled {
开发者_C百科 get { return this.m_backedVariable; }
set {
this.m_backedVariable = value;
OnPropertyChanged("IsPressAndHoldEnabled");
MessageBox.Show("Item changed: " + this.m_backedVariable);
}
}
public MainWindow() {
InitializeComponent();
this.m_checkbox.DataContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName) {
if (this.PropertyChanged != null) {
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
XAML code (MainWindow.xaml
):
<Window x:Class="MenuItemBindingTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Binding Problem Test" Width="525" Height="350">
<DockPanel>
<CheckBox x:Name="m_checkbox"
IsChecked="{Binding IsPressAndHoldEnabled}"
HorizontalAlignment="Center" VerticalAlignment="Center"
Content="Is Press and Hold enabled"/>
</DockPanel>
</Window>
The problem now is that the set accessor for the property IsPressAndHoldEnabled
is never called (ie. the message box never shows) when the user checks or unchecks the check box. It does, however, work when I rename the property to something else - like IsPressAndHoldEnabled2
.
My question now is: Why can't I use IsPressAndHoldEnabled
as name for my property? Does this have anything to do with the property Stylus.IsPressAndHoldEnabled
existing?
Interesting. I don't have answers why, but I have workarounds:
Seperating the IsPressAndHoldEnabled
property out to a seperate ViewModel class worked, unless the class was derived from FrameworkElement.
Also, changing from a regular property to a Dependency Property in the same MainWindow class worked -- the DP changed callback fires.
Have you specified TwoWay as your binding mode? Although I think CheckBox.IsChecked
defaults to TwoWay
binding mode...
I think you may have messed up your binding context, so that it is not finding the IsPressAndHoldEnabled
property. Bindings in WPF fail silently -- a royal pain if you ask me.
Check that the check-box is really bound to that property, and that the binding context really is your MainWindodw class object.
精彩评论