自定义控件ContextMenu ItemSource在设置绑定DependencyProperty时不会更新

时间:2016-08-30 09:00:43

标签: c# wpf custom-controls

我创建了一个带样式的自定义控件。一切正常,但我尝试添加的ContextMenu并没有显示任何项目。

ButtonAnalysisControl(自定义控件)

internal class ButtonAnalysisControl : Control
{
    static ButtonAnalysisControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(ButtonAnalysisControl), new FrameworkPropertyMetadata(typeof(ButtonAnalysisControl)));
    }

    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

    public Brush BackgroundBrush
    {
        get { return (Brush)GetValue(BackgroundBrushProperty); }
        set { SetValue(BackgroundBrushProperty, value); }
    }

    public ObservableCollection<ViewCommand> ChildCommands
    {
        get { return (ObservableCollection<ViewCommand>)GetValue(ChildCommandsProperty); }
        set { SetValue(ChildCommandsProperty, value); }
    }

    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(ButtonAnalysisControl), new UIPropertyMetadata(string.Empty));

    public static readonly DependencyProperty BackgroundBrushProperty =
        DependencyProperty.Register("BackgroundBrush", typeof(Brush), typeof(ButtonAnalysisControl), new UIPropertyMetadata(Brushes.Transparent));

    public static readonly DependencyProperty ChildCommandsProperty =
        DependencyProperty.Register("ChildCommands", typeof(ObservableCollection<ViewCommand>), typeof(ButtonAnalysisControl), new UIPropertyMetadata(null));

}

Generic.xaml(ButtonAnalysisControl样式)

<Style TargetType="anal:ButtonAnalysisControl">

    <Style.Triggers>
        <EventTrigger RoutedEvent="MouseDown">
            <EventTrigger.Actions>
                <BeginStoryboard>
                    <Storyboard>
                        <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="ContextMenu.IsOpen">
                            <DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True"/>
                        </BooleanAnimationUsingKeyFrames>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger.Actions>
        </EventTrigger>
    </Style.Triggers>

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="anal:ButtonAnalysisControl">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>

                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>

                    <TextBlock TextAlignment="Center"
                               VerticalAlignment="Stretch" 
                               Foreground="{StaticResource CommandBarForeground}" 
                               Background="{StaticResource MainForegroundBrush}"
                               FontFamily="{StaticResource FontFamily}"
                               FontSize="10"
                               Grid.Column="0" 
                               Grid.Row="0">
                        <TextBlock.Text>
                            <Binding Path="Text" StringFormat="{}{0}%" RelativeSource="{RelativeSource TemplatedParent}" />
                        </TextBlock.Text>                            
                    </TextBlock>
                    <Rectangle Grid.Column="0" 
                               Grid.Row="1">
                        <Rectangle.Fill>
                            <Binding Path="BackgroundBrush" RelativeSource="{RelativeSource TemplatedParent}" />
                        </Rectangle.Fill>
                    </Rectangle>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>

    <Setter Property="ContextMenu">
        <Setter.Value>
            <ContextMenu>
                <ContextMenu.ItemsSource>
                    <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="ChildCommands"/>
                </ContextMenu.ItemsSource>
                <ContextMenu.ItemContainerStyle>
                    <Style TargetType="{x:Type MenuItem}">
                        <Setter Property="MenuItem.Header" Value="{Binding Command.Text}"/>
                    </Style>
                </ContextMenu.ItemContainerStyle>
            </ContextMenu>
        </Setter.Value>
    </Setter>
</Style>

ButtonAnalysisControls是在运行时创建的,它们被设置为装饰器的内容(这在装饰器的构造函数中发生)。相关代码:

public ButtonAnalysisAdorner(UIElement adornedElement, int numberOfTimesFieldFilled, int numberOfLoggedViews, ObservableCollection<ViewCommand> childCommands)
        : base(adornedElement)
    {
        _visuals = new VisualCollection(this);
        _contentPresenter = new ContentPresenter();
        ButtonAnalysisControl bac = new ButtonAnalysisControl();
        bac.Text = percentage.ToString(CultureInfo.InvariantCulture);
        bac.BackgroundBrush = PercentColorRanges.GetColorFromPercentage((int)percentage, 0.75);
        bac.ToolTip = ToolTipValue(numberOfTimesFieldFilled, numberOfLoggedViews);
        bac.ChildCommands = childCommands;
        Content = bac;

        _visuals.Add(_contentPresenter);
    }

我用Snoop检查了ButtonAnalysisControl。 ChildCommands并不总是有项目。但我查看了一个ButtonAnalysisControl,我知道它有ChildCommands。我看到ChildCommands依赖属性有一个包含两个项的集合,ButtonAnalysisControl.ContextMenu.Items的值为0.我不知道为什么contextmenu没有任何项,我希望contextmenu被绑定使用ChildCommands。如何解决这个问题?

1 个答案:

答案 0 :(得分:-1)

我认为Templated Parent绑定不会像你想要的那样工作。 ContextMenu定义不是 模板。

您可以尝试这样的事情:

<Style TargetType="anal:ButtonAnalysisControl">
    ...    
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="anal:ButtonAnalysisControl">
                <Grid Background="Transparent" Tag="{Binding ChildCommands,RelativeSource={RelativeSource TemplatedParent}}">
                    <Grid.ContextMenu>
                        <ContextMenu ItemsSource="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
    ...

这里有几点说明:

  • 任何弹出窗口都会破坏DataContext继承,这就是我们通过Tag属性
  • 的原因
  • 网格背景是透明的,因此它会处理点击次数
  • 您可能需要重新安排MouseDown触发器以及在模板中
  • 'anal'的命名空间??