I have created a wpf application into which I have added a user control and a custom control. The custom control is used within the user control (planned to be used in many other Types of user controls).
For a quick example, the custom control has a dependency property of type Brush titled backgroundcolour, This is then set in the defualt template for the custom control as the background for the border. My thinking was that I would be able to set this value from the user control using the Command and CommandParameter properties. As i tried to do below
User Control xaml (TestControl is the custom control)
<Grid>
<Grid.Resources>
<MyNamespace:EditColourCommand x:Key="EditColour"/>
</Grid.Resources>
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Name="Test"
Header="Test"
Command="{StaticResource EditColour}"
CommandParameter="{Binding ElementName=testControl1, Path=BackgroundColour, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</ContextMenu>
</Grid.ContextMenu>
<MyNamespace:TestControl HorizontalAlignment="Left"
Margin="213,90,0,0"
x:Name="testControl1"
VerticalAlignment="Top"
Height="77"
Width="230"/>
</Grid>
My custom Control Code Behind:
public class TestControl : Control
{
static TestControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TestControl),
new FrameworkPropertyMetadata(typeof(TestControl)));
}
public static DependencyProperty BackgroundColourProperty =
DependencyProperty.Register("BackgroundColour",
typeof(Brush),
typeof(TestControl),
new PropertyMetadata(Brushes.Blue,
BackgroundColourPropertyChangedHandler));
public Brush BackgroundColour
{
get
{
return (Brush)GetValue(BackgroundColourProperty);
}
set
{
SetValue(BackgroundColourProperty, value);
}
}
public static void BackgroundColourPropertyChangedHandler(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
}
}
Finally, The Command
public class EditColourCommand : ICommand
{
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
parameter = Brushes.Black;
}
}
The command gets fired and it has the defualt value in this case blue as a parameter but it never sets the value to black. Can someone push me in the right direction please?
Just modify your Command to
and modify your command execute to
you can’t expect the binding to work like you did in the CommandParameter.