gpt4 book ai didi

c# - 将颜色绑定(bind)到单例

转载 作者:行者123 更新时间:2023-11-30 15:15:59 25 4
gpt4 key购买 nike

我正在开发一个 Xamarin 表单应用程序,我决定为了使整个应用程序的样式更容易一致,我将在单例类中保留诸如调色板之类的东西,然后在 XAML 中将属性绑定(bind)到它。

我最初将其实现为静态类以使用 x:Static,但很快意识到这无法真正工作,因为我需要 INotifyPropertyChanged,这意味着当我运行该应用程序时,一切都是白色的。

我现在已经将该类实现为一个合适的单例,如下所示:

public class Colors : INotifyPropertyChanged
{
private Color primary;
public Color Primary
{
get
{
return primary;
}
set
{
primary = value;
NotifyPropertyChanged("Primary");
}
}

private Color success;
public Color Success
{
get
{
return success;
}
set
{
success = value;
NotifyPropertyChanged("Success");
}
}

private Color failure;
public Color Failure
{
get
{
return failure;
}
set
{
failure = value;
NotifyPropertyChanged("Failure");
}
}



private Colors()
{
Primary = new Color(142, 190, 232);
Success = new Color(134, 232, 133);
Failure = new Color(255, 265, 173);
}

private static Colors instance;

public static Colors Instance
{
get
{
if(instance == null)
{
instance = new Colors();
}
return instance;
}
}

// INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(String info)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(info));
}
}
}

我一直在尝试使用 {Binding Source={local:Colors.Instance.Primary}} 作为这些颜色的绑定(bind),但我的 XAML 无法编译并出现错误 MarkupExtension找不到 local:Colors.Instance 这不是很有用。

关于此的 Microsoft 文档也非常无用,所以我有点不知所措。谁能指出我正确的方向?

最佳答案

由于您不打算在运行时更改样式,静态资源在这种情况下会有所帮助。

您可以在 App.xaml 中使用 ResourceDictionary,它将在整个应用程序中访问。

<?xml version="1.0" encoding="utf-8"?><Application
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Test.App">
<Application.Resources>
<ResourceDictionary>
<Color
x:Key="primary">#03A9F4</Color>
<Color
x:Key="primary_dark">#0288D1</Color>
<Color
x:Key="primary_light">#B3E5FC</Color>
<Color
x:Key="BlueToolBarColor">#012E5B</Color>
<Style
x:Key="HeaderText"
TargetType="Label">
<Setter
Property="FontAttributes"
Value="Bold" />
</Style>
</ResourceDictionary>
</Application.Resources>

您可以像这样在 XAML 布局中使用这些资源,

<Label
Text="Hello"
TextColor="{StaticResource primary_dark}"
Style="{StaticResource HeaderText}" />

关于c# - 将颜色绑定(bind)到单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51010079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com