【发布时间】:2021-10-25 17:30:04
【问题描述】:
我正在做一个使用ModernWPF 的项目。我想将TitleBar.Background 绑定到GetBG。
这是我的代码:
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ModernWpf;
namespace TestApp.Desktop
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Color GetBG()
{
var bc = new BrushConverter();
if (ModernWpf.ThemeManager.GetRequestedTheme(window).ToString() == "Black" || ModernWpf.ThemeManager.GetRequestedTheme(window).ToString() == "Dark")
{
return (Color)ColorConverter.ConvertFromString("#1E1E1E");
}
else { return (Color)ColorConverter.ConvertFromString("#E6E6E6"); }
}
}
}
}
<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"
mc:Ignorable="d"
ui:ThemeManager.RequestedTheme="Light"
<!---Here's where i want to use the binding.--->
ui:TitleBar.Background="{GetBG}"
ui:TitleBar.IsIconVisible="False"
ui:ThemeManager.IsThemeAware="True"
xmlns:ui="http://schemas.modernwpf.com/2019"
ui:WindowHelper.UseModernWindowStyle="True"
Title="TestApp" Height="850" Width="1260">
<Grid>
</Grid>
编辑,我重命名了 GetBG 并在 MainWindow.cs 文件中公开:
public Color ThemeAwareBackground()
{
var bc = new BrushConverter();
if (ModernWpf.ThemeManager.GetRequestedTheme(window).ToString() == "Black" || ModernWpf.ThemeManager.GetRequestedTheme(window).ToString() == "Dark")
{
return (Color)ColorConverter.ConvertFromString("#1E1E1E");
}
else { return (Color)ColorConverter.ConvertFromString("#E6E6E6"); }
}
谢谢。
【问题讨论】:
-
使其属性不是本地函数,然后像
{Binding ThemeAwareBackground, RelativeSource={RelativeSource Self}}一样绑定它 -
它不起作用。它显示一个错误,说 GetBG 不存在。 XLS0432 在类型“MainWindow”中找不到属性“GetBG”。
-
让它成为非本地函数的属性 ThemeAwareBackground(因为调用属性
GetBG不好)它只能有getter,但应该是公开的 -
仍然没有成功。它仍然显示 ThemeAwareBackground 不存在的错误。
-
ThemeAwareBackground 不存在 是的,我敢打赌……你添加了吗?你有
Color GetBG()使它成为MainWindow的属性,称为ThemeAwareBackground(因为显然你不能绑定到方法 - 特别是本地)
标签: c# wpf xaml data-binding