我在運行時動態創建窗口。我有自定義按鈕。我需要在運行時根據請求獲得「是,否」,「確定,取消」,「確定」,「是,否,取消」。我在這裏有照片。 這張圖片描繪的是,當按鈕的水平對齊是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>
非常感謝。這樣可行。 – Sailoosha