ModernWPF项目中将自定义主题色方法绑定到TitleBar.Background的问题
实现方法
WPF 原生绑定不支持直接绑定普通方法,你需要将逻辑调整为支持变更通知的属性,同时监听主题切换事件实现背景色自动更新,具体修改如下:
1. 调整后台 C# 代码
你需要给 MainWindow 实现 INotifyPropertyChanged 接口,将原方法改为只读通知属性,同时订阅 ModernWPF 主题变更事件,触发时主动通知 UI 更新属性值:
using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows; using System.Windows.Media; using ModernWpf; namespace TestApp.Desktop { public partial class MainWindow : Window, INotifyPropertyChanged { // 实现属性变更通知接口 public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } // 改为Brush类型的通知属性,匹配TitleBar.Background的类型要求 public Brush ThemeAwareBackground { get { var currentTheme = ThemeManager.GetActualTheme(this); if (currentTheme == ApplicationTheme.Dark || currentTheme == ApplicationTheme.Black) { return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#1E1E1E")); } return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#E6E6E6")); } } public MainWindow() { InitializeComponent(); // 订阅主题变更事件,主题切换时主动通知属性更新 ThemeManager.Current.ActualThemeChanged += (s, e) => { OnPropertyChanged(nameof(ThemeAwareBackground)); }; } } }
2. 调整XAML绑定写法
首先修正命名空间的声明顺序(xmlns 声明要放在属性引用之前),然后修改 TitleBar.Background 的绑定表达式,通过 ElementName 绑定到窗体自身的属性即可:
<Window x:Name="window" x:Class="OpenRelease.Desktop.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:TestApp" xmlns:ui="http://schemas.modernwpf.com/2019" mc:Ignorable="d" ui:ThemeManager.RequestedTheme="Light" ui:TitleBar.Background="{Binding ThemeAwareBackground, ElementName=window}" ui:TitleBar.IsIconVisible="False" ui:ThemeManager.IsThemeAware="True" ui:WindowHelper.UseModernWindowStyle="True" Title="TestApp" Height="850" Width="1260"> <Grid> </Grid> </Window>
内容的提问来源于stack exchange,提问作者AZ Software
相关产品推荐
相关产品推荐

