ToolBar更改所选项目

时间:2011-02-24 12:44:48

标签: wpf toolbar

我创建了一个工具栏,它有3个按钮类型项,并且有足够的宽度来显示1个项目(其余部分在下拉框中)。如何更改当我单击下拉框中的项目时,可见项目更改为该项目的行为?

1 个答案:

答案 0 :(得分:1)

您可以将点击的项目的Toolbar.OverflowMode更改为OverflowMode.Never 以及其他项目的Toolbar.OverflowMode到OverflowMode.Always

示例:

<ToolBar Width="80" HorizontalAlignment="Left" VerticalAlignment="Top">
  <Button Name="btn1" ToolBar.OverflowMode="Never" Click="btn1_Click">Button 1</Button>
  <Button Name="btn2" ToolBar.OverflowMode="Always" Click="btn2_Click">Button 2</Button>
  <Button Name="btn3" ToolBar.OverflowMode="Always" Click="btn3_Click">Button 3</Button>
</ToolBar>


private void btn1_Click(object sender, RoutedEventArgs e)
{
  ToolBar.SetOverflowMode(btn1, OverflowMode.Never);
  ToolBar.SetOverflowMode(btn2, OverflowMode.Always);
  ToolBar.SetOverflowMode(btn3, OverflowMode.Always);
}

private void btn2_Click(object sender, RoutedEventArgs e)
{
  ToolBar.SetOverflowMode(btn1, OverflowMode.Always);
  ToolBar.SetOverflowMode(btn2, OverflowMode.Never);
  ToolBar.SetOverflowMode(btn3, OverflowMode.Always);
}

private void btn3_Click(object sender, RoutedEventArgs e)
{
  ToolBar.SetOverflowMode(btn3, OverflowMode.Never);
  ToolBar.SetOverflowMode(btn1, OverflowMode.Always);
  ToolBar.SetOverflowMode(btn2, OverflowMode.Always);
}

更通用的方法:

  UIElement element = sender as UIElement;
  if (element != null) 
  {
    ToolBar.SetOverflowMode(element, OverflowMode.Never);

    foreach (var child in toolbar.Items) 
    {
      if (child is UIElement && child != element) 
      {
        ToolBar.SetOverflowMode((UIElement)child, OverflowMode.Always);
      }
    }
  }