问题
My objective here is to disable and enabled some items on a GUI based on the value of a flag that will be changed during execution in the code behind for the window. I've set up a DependencyProperty to accomplish this. I believe that all I have to do is bind the this property to the appropriate "IsEnabled" properties and everything should work. Something is not hooking up properly so nothing is happening. Am I missing some syntax here or something?
Here is the binding in WPF (MainWindow.xaml):
<MenuItem Name="LoggingMenuItem" Header="_Logging" IsCheckable="True" Checked="LoggingMenuItem_Checked" IsEnabled="{Binding ElementName=IsMonitoring}" />
Here is the declaration of the "IsMonitoring" Property in the code behind (MainWindow.xaml.cs):
public static readonly DependencyProperty IsMonitoringProperty =
DependencyProperty.Register("IsMonitoring", typeof(Boolean), typeof(Window));
public bool IsMonitoring
{
get { return (bool)GetValue(IsMonitoringProperty); }
set { SetValue(IsMonitoringProperty, value); }
}
回答1:
Your binding is not configured correctly. The ElementName attribute should point to an "Element" (that is control) within the Window and you should use the Path attribute to specify the property name.
In your case, you want to give the Window a name to use. I tend to use the name "this" but of course it could be whatever you want.
<Window x:Name="this"
...
>
...
<MenuItem IsEnabled="{Binding ElementName=this, Path=IsMonitoring}" />
...
</Window>
来源:https://stackoverflow.com/questions/8070406/dependencyproperty-binding-not-working