2010-06-15 45 views
0

我在ScrollViewer中有一個ItemsControl,並且當這些項目超過ScrollViewer的寬度時,它們被放入一個ContextMenu中,並顯示爲DropDown。我的問題是,當上下文菜單第一次加載時,它節省了菜單的大小,並且在添加/刪除更多命令時不會重新繪製。WPF - 項目更改時重繪上下文菜單?

例如,面板有3個命令。 1是可見的,2是在菜單中。查看菜單會顯示2個命令並繪製控件,但如果調整面板的大小使其可見並且只有1個命令在菜單中,則不會重新繪製菜單以消除該第二個菜單項。或者更糟的是,如果你退縮的面板使顯示沒有命令和所有3個都在菜單中,它只會顯示前2

https://i193.photobucket.com/albums/z197/Lady53461/ContextMenuRedraw.jpg

這裏是我的代碼:

<Button Click="DropDownMenu_Click" 
     ContextMenuOpening="DropDownMenu_ContextMenuOpening"> 

    <Button.ContextMenu> 
     <ContextMenu ItemsSource="{Binding Path=MenuCommands}" Placement="Bottom"> 
      <ContextMenu.Resources> 
       <Style TargetType="{x:Type MenuItem}"> 
        <Setter Property="Command" Value="{Binding Path=Command}" /> 
        <Setter Property="Visibility" Value="{Binding Path=IsVisible, Converter={StaticResource ReverseBooleanToVisibilityConverter}}"/> 
       </Style> 
      </ContextMenu.Resources> 
      <ContextMenu.ItemTemplate> 
       <DataTemplate> 
        <TextBlock Text="{Binding Path=DisplayName}" /> 
       </DataTemplate> 
      </ContextMenu.ItemTemplate> 
     </ContextMenu> 
    </Button.ContextMenu> 
</Button> 

代碼背後:

 void DropDownMenu_ContextMenuOpening(object sender, ContextMenuEventArgs e) 
    { 
     Button b = sender as Button; 
     b.ContextMenu.IsOpen = false; 
     e.Handled = true; 
    } 

    private void DropDownMenu_Click(object sender, RoutedEventArgs e) 
    { 
     Button b = sender as Button; 

     ContextMenu cMenu = b.ContextMenu; 
     if (cMenu != null) 
     { 
      cMenu.PlacementTarget = b; 
      cMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom; 
      cMenu.IsOpen = true; 
     } 
    } 

我一直在使用InvalidateVisual和傳遞一個空委託上渲染,試圖迫使重繪試過,但沒有作品。我使用.Net 4.0。

+0

只是好奇你爲什麼要取消ContextMenuOpening事件?是因爲你只希望它顯示在左鍵單擊還是其他東西? – devios1 2010-06-15 12:55:39

+0

是的,我想在ButtonClick上顯示菜單,而不是R鼠標按鈕按下 – Rachel 2010-06-15 12:58:02

回答

2

是MenuCommands集合?如果是,它是一個ObservableCollection?

如果您綁定的集合到ItemsControl的,該集合必須實現INotifyCollectionChanged接口讓的ItemsControl知道集合中的項目數量發生了變化,從而使該控件可以「重繪」本身。

+0

它是一個繼電器命令 – Rachel 2010-06-15 14:19:58

+0

ObservableCollection好了,但我沒有看到任何代碼改變MenuCommands集合!代碼的哪部分改變了它? – decyclone 2010-06-15 15:28:27

+0

ScrollViewer.SizeChanged事件修改了MenuCommands集合,並根據該對象是否在ScrollViewers視口內或不是... hrrm修改ObservableCollection中的項目不會觸發ObservableCollection已更改事件,從而更改IsVisible屬性? – Rachel 2010-06-15 16:00:15