5

我有一个 WPF 窗口,它有一个ToolBar. 我的虚拟机中有一组要绑定的对象。它们显示为按钮,但它们总是被推到ToolBar. 如何使这些按钮出现在标准部分ToolBar

我有以下 XAML:

<ToolBarTray Grid.Row="1">
    <ToolBar ItemsSource="{Binding Path=MyList}" >
        <ToolBar.ItemTemplate>
            <DataTemplate  >
                <Button ToolTip="{Binding ButtonName}" 
                        Command="{Binding Path=ButtonCommand}" >
                    <Button.Content>
                        <Image Width="32" Height="32" Source="{Binding ImageSource}"/>
                    </Button.Content>
                </Button>
            </DataTemplate>
        </ToolBar.ItemTemplate>
    </ToolBar>
</ToolBarTray>

我有以下 C#:

public List<MyClass> MyList
    {
        get
        {
            return new List<MyClass>
                       {
                           new MyClass{ButtonName="Button1",ImageSource=@"C:\Projects\WpfApplication2\WpfApplication2\Employee.png"},
                           new MyClass{ButtonName="Button2",ImageSource=@"C:\Projects\WpfApplication2\WpfApplication2\Employee.png"},
                           new MyClass{ButtonName="Button3",ImageSource=@"C:\Projects\WpfApplication2\WpfApplication2\Employee.png"},
                           new MyClass{ButtonName="Button4",ImageSource=@"C:\Projects\WpfApplication2\WpfApplication2\Employee.png"},
                       };

        }
    }

这是视觉结果:

替代文字

4

4 回答 4

4

工具栏中有一个错误,如果您重新调整窗口大小,问题就会消失。

解决方案是使用另一个控件,例如:

public class WorkaroundToolBar : ToolBar
{
    private delegate void IvalidateMeasureJob();

    public override void OnApplyTemplate()
    {
        Dispatcher.BeginInvoke(new IvalidateMeasureJob(InvalidateMeasure), 
                                     DispatcherPriority.Background, null);
        base.OnApplyTemplate();
    }
}

查看此线程以获取更多信息

于 2009-10-19T18:40:02.263 回答
1

您还可以将 xaml 中工具栏的高度设置为对我有用的合理值。

于 2010-01-18T10:39:39.260 回答
1

To add to Eduardo's, I had to slightly tweak this since my item source was getting populated asynchronously, some time after the initial UI is displayed:

public class ToolBar : System.Windows.Controls.ToolBar
{
    public override void OnApplyTemplate ()
    {
        Dispatcher.BeginInvoke ((Action)(InvalidateMeasure), DispatcherPriority.Background, null);
        base.OnApplyTemplate ();
    }
    protected override void OnItemsChanged (NotifyCollectionChangedEventArgs e)
    {
        base.OnItemsChanged (e);
        Dispatcher.BeginInvoke ((Action)(InvalidateMeasure), DispatcherPriority.Background, null);
    }
}

This was enough to catch all edge cases and have the overflow properly happen as needed after population of the items.

于 2015-11-02T17:45:02.393 回答
0

设置'ToolBar.OverflowMode="Never"'。

可以在此处找到有关工具栏溢出的更多信息。

于 2020-07-13T13:55:30.237 回答