簡體   English   中英

如何在后面的代碼中使用WPF C#創建帶有圖像的自定義MessageBox?

[英]How to create, in code behind, a Custom MessageBox with Images in WPF C#?

如何在WPF C#中使用背后的代碼(沒有XAML)創建自定義MessageBox(對話框)? 我用谷歌搜索,似乎找不到解決方案。 我想要一個帶有圖像和其他控件的MessageBox。

您可以使用以下解決方案:

    string messageBoxText = "Do you want to save changes?";
    string caption = "Your caption";
    MessageBoxButton button = MessageBoxButton.YesNoCancel;
    MessageBoxImage icon = MessageBoxImage.Warning;
    MessageBox.Show(messageBoxText, caption, button, icon);

查看這篇文章,如果需要,您可以將所有Xaml重新編碼為“自定義對話框”段落中的純c#。

或者您可以創建自己的Window並使用MyWindow.ShowDialog()

像下面的代碼:

    Window wnd = new Window();
    Grid grid = new Grid();
    wnd.Height = 200;
    wnd.Width = 150;
    grid.RowDefinitions.Add(new RowDefinition {Height = new GridLength(100) });
    grid.RowDefinitions.Add(new RowDefinition {Height = GridLength.Auto });
    wnd.Content = grid;
    Image img = new Image();
    Button btn = new Button();
    btn.Content = "OK";
    btn.VerticalAlignment = VerticalAlignment.Bottom;
    Grid.SetRow(img, 0);
    Grid.SetRow(btn, 1); 
    grid.Children.Add(img);
    grid.Children.Add(btn);
    wnd.Owner = MyMainWindow;
    wnd.ShowDialog();

為什么不只在XAML中創建自定義窗口,然后在隱藏代碼中使用showDialog()?

XAML中的所有內容都可以用純c#重寫:

<Window>
 <Grid>
  <Grid.ColumnDefinition Width="50" />
  <Grid.ColumnDefinition Width="*">
  <Label Grid.Column="0" Content="Hello World!" />
 </Grid>
</Window>

看起來像這樣:

public void MakeWin(DependencyObject owner)
{
   MakeWin(Window.GetWindow(owner));
}

public void MakeWin(Window owner)
{
   Window window = new Window();
   Grid grid = new Grid();
   grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(50) });
   grid.ColumnDefinitions.Add(new ColumnDefinition {Width = GridLength.Auto});
   window.Content = grid;

   Label label = new Label { Content = "Hello World!" };
   Grid.SetColumn(label, 0); // Depandency property
   grid.Children.Add(label);

   window.Owner = owner;
   window.ShowDialog();
}

對於圖像,WPF工具包中提供了源代碼(或預構建的代碼), 網址為http://wpftoolkit.codeplex.com/wikipage?title=MessageBox&version=31

如果您需要的不僅僅是圖像,一行文本和幾個按鈕,那么您可能應該只考慮使用通過ShowDialog()調用的新Window

我已經實現了WPF MessageBox,它具有與普通界面完全相同的界面,並且還可以通過標准WPF控件模板完全自定義:

可自定義的WPF消息框

特征

  • WPFMessageBox類具有與當前WPF MessageBox類完全相同的接口。
  • 作為自定義控件實現,因此可以通過標准WPF控件模板完全自定義。
  • 有一個默認控件模板,看起來像標准的MessageBox。
  • 支持所有常見的消息框類型:錯誤,警告,問題和信息。
  • 具有與打開標准MessageBox時相同的“嗶”聲。
  • 按Escape按鈕時,與標准MessageBox支持相同的行為。
  • 提供與標准MessageBox相同的系統菜單,包括在消息框處於“是-否”模式時禁用“關閉”按鈕。
  • 處理從右對齊和從右到左的操作系統,與標准MessageBox相同。
  • 提供支持將所有者窗口設置為WinForms Form控件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM