I am trying to pass the parent Window
in to a command so that it can be used for a RoutedCommand
. Is there any way to do this with Dependency Properties
? Ive seen a lot of questions that say this isn't possible because it isn't part of the visual tree, but the below works:
<Button CommandParameter="{Binding ElementName=Main}" .../>
The parameter is actually set as Main
(the parent Window). So, how can I do this on my custom object with a Dependency Property
?
The error I get when I try to set it on my own object DP:
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:(no path); DataItem=null; target element is 'CommandGroup' (HashCode=25702951); target property is 'CommandParameter' (type 'Object')
My class is as follows:
public class CommandGroup : DependencyObject, ICommand
{
public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof (object), typeof (CommandGroup));
public object CommandParameter
{
get { return (object)GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
....
}
I want to set the XAML as below:
<Button>
<Button.Command>
<CommandGroup CommandParameter={Binding ElementName=Main}>
...
Because CommandParameter is not a visual or logical tree element, it cannot inherit DataContext.
...but when your object is Freezable
, it can inherit DataContext.
public class CommandGroup : Freezable, ICommand
{
public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof (object), typeof (CommandGroup));
public object CommandParameter
{
get { return (object)GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
protected override Freezable CreateInstanceCore()
{
return new CommandGroup();
}
}
See: https://thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.