Home > database >  how can I make a topmost checkbox wpf C#
how can I make a topmost checkbox wpf C#

Time:08-21

So I have a main windows that loads a page this page is a settings page and I have the setting topmost, because I am using a page to display the buttons I did:

if(TopMostCheckBox.IsChecked == true)
{
    MainWindow main = new MainWindow();
    main.Topmost = true;
}

if(TopMostCheckBox.IsChecked == false)
{
    MainWindow main = new MainWindow();
    main.Topmost = false;
}

but for some reason when I load my program I check box doesn't check top most so how can I make my page toggle top most for my main window.

CodePudding user response:

Answering your Question title:

how can I make a topmost checkbox WPF C#

As a Minimal, Reproducible Example the following would apparently work in the MainWindow code-behind of a newly created WPF project:

XAML:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <CheckBox Checked="CheckBox_CheckedChanged"
                  Unchecked="CheckBox_CheckedChanged"/>
    </Grid>
</Window>

MainWindow.CS:

using System.Windows;
using System.Windows.Controls;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void CheckBox_CheckedChanged(object sender, RoutedEventArgs e)
        {
            Topmost = ((CheckBox)sender).IsChecked == true;
        }
    }
}

CodePudding user response:

You're creating a new instance of mainwindow rather than referencing the existing instance.

        if (TopMostCheckBox.IsChecked == true)
        {
            var main = Application.Current.MainWindow as MainWindow;
            main.Topmost = true;
        }

The above assumes you've not given mainwindow a different name to the default. You might find you have to set topmost false and then true to get it to respond.

  • Related