WPF:切换窗口样式

时间:2013-08-22 11:36:29

标签: c# wpf button resourcedictionary mergeddictionaries

我有一个程序有一些按钮,其中一个用于切换“主题”。 有两个主题,一个是普通的Windows主题,另一个叫做Style2。

这就是我尝试切换的方式

    private bool UsingWindowsStyle = true;
    private ResourceDictionary Style2= new ResourceDictionary() { Source = new Uri("/...;component/Resources/DefaultStyles.xaml", UriKind.RelativeOrAbsolute) };

    private void SwitchButton_Click(object sender, RoutedEventArgs e)
    {
        if (UsingWindowsStyle)
        {
            Resources.MergedDictionaries.Add(Style2);
            UsingWindowsStyle = false;
        }
        else
        {
            Resources.MergedDictionaries.Remove(Style2);
            UsingWindowsStyle = true;
        }
    }

我的问题是,当我使用这个程序时,按下这个Button,就会发生这种情况:

打开窗口使用Windows主题正常运行程序。

SwitchButton首次点击程序将视觉效果更改为Style2主题。所有程序的按钮都正常运行。

SwitchButton第二次点击程序恢复为Windows主题,但程序中的所有按钮都可以恢复工作。

要考虑的要点

  1. 此时程序不会抛出任何异常。
  2. 调试代码,似乎在第二次点击后,程序没有进入SwitchButton_Click方法。
  3. 我尝试阅读点击EventHandler,但没有用。

    SwitchButton.Click += new RoutedEventHandler(SwitchButton_Click);
    
  4. 提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我建议你太努力了。您需要做的就是更改窗口本身的样式。单独留下词典。 : - )

以下是从可用样式列表中单击时更改窗口样式的示例。

How to style

我的命令归结为

             //Here I am changing the style on the window
            NewWindow.Style = ((StyleDetailsViewModel)x).Style;
            NewWindow.Show();

使用各种输入数据

   public StylingViewModel(Func<string, Style> findStyle)
    {     
        Styles = new StyleDetailsViewModel[]
        {
            new StyleDetailsViewModel
            { 
                Name = "None",  
                Description = "Completely remove all styling and show the raw NavigationWindow including default navigation elements", 
                WindowStyleNone = false,
                Image = "\\Resources\\WindowStyleNone.png"
            },
            new StyleDetailsViewModel
            { 
                Name = "PlainWindow", 
                Style = findStyle("PlainWindow"),  
                Description = "Hides the navigation elemetns of the NavigationWindow to make it look just like a normal window", 
                WindowStyleNone = false,
                Image = "\\Resources\\WindowStylePlain.png"
            },
            new StyleDetailsViewModel
            { 
                Name = "Windows 7",  
                Style = findStyle("Win7NavigationWindow"),  
                Description = "Uses glass effects to create a window that looks almost identical to the control panel from Windows 7.", 
                WindowStyleNone = false,
                Image = "\\Resources\\WindowStyleWin7Nav.png"
            },

    this.DataContext = new StylingViewModel(x => (Style)this.FindResource(x));

还要注意某些只能在窗口打开之前设置的窗口属性,例如WindowStyle="None",如果您正在进行自定义镶边操作,则需要{{1}}。