如何让WPF工具栏在不使用expander的情况下绑定到我的VM中的集合
我有一个WPF窗口,它有一个如何让WPF工具栏在不使用expander的情况下绑定到我的VM中的集合,wpf,data-binding,mvvm,toolbar,Wpf,Data Binding,Mvvm,Toolbar,我有一个WPF窗口,它有一个工具栏。我的虚拟机中有一个绑定到的对象集合。它们显示为按钮,但总是被推到工具栏的展开下拉部分。如何使这些按钮显示在工具栏的标准部分中 我有以下XAML: <ToolBarTray Grid.Row="1"> <ToolBar ItemsSource="{Binding Path=MyList}" > <ToolBar.ItemTemplate> <DataTemplate &g
工具栏
。我的虚拟机中有一个绑定到的对象集合。它们显示为按钮,但总是被推到工具栏的展开下拉部分。如何使这些按钮显示在工具栏的标准部分中
我有以下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>
我有以下几点建议:
公共列表MyList
{
得到
{
返回新列表
{
新MyClass{ButtonName=“Button1”,ImageSource=@“C:\Projects\WpfApplication2\WpfApplication2\Employee.png”},
新MyClass{ButtonName=“Button2”,ImageSource=@“C:\Projects\WpfApplication2\WpfApplication2\Employee.png”},
新MyClass{ButtonName=“Button3”,ImageSource=@“C:\Projects\WpfApplication2\WpfApplication2\Employee.png”},
新MyClass{ButtonName=“Button4”,ImageSource=@“C:\Projects\WpfApplication2\WpfApplication2\Employee.png”},
};
}
}
这是视觉效果:
工具栏中有一个bug,如果重新调整窗口大小,问题就会消失
解决方案使用另一个控件,如:
public class WorkaroundToolBar : ToolBar
{
private delegate void IvalidateMeasureJob();
public override void OnApplyTemplate()
{
Dispatcher.BeginInvoke(new IvalidateMeasureJob(InvalidateMeasure),
DispatcherPriority.Background, null);
base.OnApplyTemplate();
}
}
查看更多信息您还可以将xaml中工具栏的高度设置为一个合理的值,这对我很有用。要添加到Eduardo的工具栏中,我必须稍微调整一下,因为我的项目源是异步填充的,在初始UI显示一段时间后:
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);
}
}
这足以捕获所有边缘情况,并在填充项目后根据需要正确发生溢出。设置“ToolBar.OverflowMode=”Never“
有关工具栏溢出的更多信息,请参见。如果我将工具栏的静态宽度设置为500,同样的视觉效果也会出现,请您进一步说明specific@Shimmy,我想我不能说得更具体,但我会尽力的。我希望工具栏中的按钮显示在工具栏的标准(非溢出)部分不幸的是,这不起作用。你是对的,当我调整屏幕大小时,按钮会如预期的那样出现。在我的机器上工作,试试这个赤裸裸的示例。我做的这个解决方案也不直接适用于我。我还没有检查你提供的样品。对不起,爱德华多,我的错。这个解决方案有效。我忘了更换,不幸的是,这不能完全起作用。如果一开始按钮集合为空,则启动应用程序并通过代码动态添加一些按钮,之后(变通方法)工具栏在视觉上仍然无效。它看起来就像上面的屏幕截图,只要调整窗口大小,它就会正确地重新绘制。还有什么提示吗?你应该对你的答案更有信心。
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);
}
}