简体   繁体   中英

C# wpf open new window form list combobox

Help me. I want to open any window in a combobox list. This is the code I use when opening an existing window.

windowname wdname = new windowname();
                wdname.ShowDialog();

But now I have a window list. I want to open a window when I select in combobox. What should I do. Thanks so much for help.

You can add a listener for SelectionChanged event and handle user selection.

XAML:

<ComboBox SelectionChanged="ComboBoxSelectionChanged">
    <ComboBoxItem Tag="UsersWindow">Users Window</ComboBoxItem>
    <ComboBoxItem Tag="SettingsWindow">Settings Window</ComboBoxItem>
    <ComboBoxItem Tag="CustomersWindow">Customers Window</ComboBoxItem>
</ComboBox>

Code-behind

public partial class MainWindow
{
    public List<Window> Windows { get; set; }

    public MainWindow()
    {
        InitializeComponent();

        Windows = new List<Window>
        {
            new Window { Name = "UsersWindow" },
            new Window { Name = "SettingsWindow" },
            new Window { Name = "CustomersWindow" },
        };
    }        

    private void ComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var comboBox = (ComboBox)e.Source;

        if (comboBox.SelectedItem == null) return;

        var selectedItem = (ComboBoxItem)comboBox.SelectedItem;
        var window = Windows.FirstOrDefault(w => w.Name.Equals(selectedItem.Tag));

        if (window == null) return;

        window.ShowDialog();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM