由于ToolBar上的控件只有左对齐和右对齐之说,无法向DockPanel那样将控件左右分别靠边,如果指望将DockPanel套在ToolBar中就能实现,那就错了。
但是可以换一个思路。
在控件之间插入一个label控件,为其增加HorizontalAlignment="Stretch"属性,并绑定其Width属性。xaml代码如下:
<ToolBar Height="40" HorizontalAlignment="Stretch" VerticalAlignment="Top" Background="LightGray">
<ComboBox Name="comboBoxConversations" Height="24" Width="50" ></ComboBox>
<Label Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ToolBar}, Path=ActualWidth, Converter={StaticResource WidthCaculater}, ConverterParameter=320}" HorizontalAlignment="Stretch" ToolBar.OverflowMode="Never"/>
<TextBox/>
</ToolBar>
当然还得定义一个Converter类,如下:
class WidthConverter : IValueConverter
{
#region IValueConverter メンバー
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Math.Max(System.Convert.ToDouble(value) - System.Convert.ToDouble(parameter), 0.0);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
通过减法实现动态的改变label的宽度,从而定位toolbar上的控件。
本文介绍了一种在WPF中使ToolBar控件居中的方法,通过使用Label控件并结合数据绑定及自定义转换器来动态调整宽度。

5万+

被折叠的 条评论
为什么被折叠?



