我在运行时动态创建一个窗口。我有自定义按钮。我需要根据请求在运行时相应地获得“是,否”,“确定,取消”,“确定”,“是,否,取消”。我在这里有照片。 这张图片描绘了当按钮的水平对齐方式为 Right 时。我没有将两个按钮都放在右边。在这种情况下,你能帮帮我吗?我还在下面分享了我的代码。问题是 Button Collection 将行划分为我们需要的按钮数量。
我的代码。
internal sealed class MessageBoxModule : Window
{
private static Style _ctrlButtonStyle;
public new static readonly DependencyProperty TitleProperty;
public static readonly DependencyProperty MessageProperty;
public static readonly DependencyProperty ButtonCollectionProperty =
DependencyProperty.Register("ButtonCollection", typeof(IList<Button>), typeof(MessageBoxModule), new PropertyMetadata(new List<Button>()));
public MessageBoxModule()
{
WindowStartupLocation = WindowStartupLocation.CenterScreen;
AllowsTransparency = true;WindowStyle = WindowStyle.None;
//...
}
}
public static MessageBoxResult Show(Window owner, string messageBoxText, string caption)
{
var mbox = new MessageBoxModule();
boxes.Add(mbox); mbox.Message = messageBoxText; mbox.Title = caption;
switch (button)
{
case MessageBoxButton.OKCancel:
mbox.ButtonCollection.Add(CreateButton(mbox, "OK"));
mbox.ButtonCollection.Add(CreateButton(mbox, "Cancel"));
break;
//.... And so on.
}
var result = mbox.ShowDialog();
switch (button)
{
case MessageBoxButton.YesNoCancel://and so on.
}
}
private static Button CreateButton(string content, bool isCancel, RoutedEventHandler clickHandler)
{
Button btn = new Button();
btn.Padding = new Thickness(20, 3, 20, 3);
btn.Content = content;
btn.Style = _ctrlButtonStyle;//Custom button Style in WPF
btn.Click += clickHandler;
btn.Height = 25; btn.Width = 75;
return btn;
}
MessageBox Style:这里,垂直和水平对齐设置为居中。即使我将其更改为正确的,我也遇到了图片中的问题。
<ControlTemplate x:Key="MessageBoxCt"
TargetType="{x:Type Helper:MessageBoxModule}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="3" Margin="8">
<Grid x:Name="grid">
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<TextBlock x:Name="textBlock" Text="{TemplateBinding Title}"/>
<Border Grid.Row="0" BorderThickness="0,0,0,1"/>
<TextBlock Text="{TemplateBinding Message}"Grid.Row="1"Margin="10"TextTrimming="None"Foreground="{TemplateBinding Foreground}"
TextWrapping="WrapWithOverflow"FontSize="{TemplateBinding FontSize}" />
<ItemsControl Grid.Row="2"Margin="10"ItemsSource="{TemplateBinding ButtonCollection}"
ScrollViewer.VerticalScrollBarVisibility= "Disabled"HorizontalContentAlignment="Right"VerticalContentAlignment="Center"Padding="0,0,5,0">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="1" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Grid>
</Border>
</ControlTemplate>
请您参考如下方法:
使用 UniformGrid 时,行中的每个项目都采用相同的宽度,使用 HorizontalContentAlignment="Right" 时,其中的按钮将右对齐。请尝试 HorizontalAlignment="Right" 而不是右对齐完整的 ItemsControl:
<ItemsControl Grid.Row="2"
...
HorizontalAlignment="Right">
...
</ItemsControl>
