C# 如何在Xamarin中使用开关更改页面背景色
当开关为真和假时,我想更改页面的背景色。到目前为止,我已经完成了C# 如何在Xamarin中使用开关更改页面背景色,c#,xaml,xamarin.forms,C#,Xaml,Xamarin.forms,当开关为真和假时,我想更改页面的背景色。到目前为止,我已经完成了 <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:d="http://xamarin.com/schemas/2014/forms/design" xmlns:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:App9"
mc:Ignorable="d"
x:Class="App9.MainPage" x:Name="main" BackgroundColor="{Binding Display}">
<ContentPage.BindingContext>
<local:Class1/>
</ContentPage.BindingContext>
<StackLayout>
<Switch x:Name="toggle" Toggled="Switch_Toggled"/>
</StackLayout>
和1级
public class Class1 : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private Color display;
public Color Display
{
get
{
return display;
}
set
{
if (display != value)
{
display = value;
NotifyPropertyChanged(nameof(Display));
}
}
}
所以当开关在后台时应该是白色的。但它不会改变。我不知道如何使用INotifyPropertyChanged我相信最简单的方法就是使用触发器 触发器允许您在XAML中声明性地表示动作,这些动作根据事件或属性更改更改控件的外观。() 您可以将
数据触发器
绑定到开关的值
,以更改另一个控件的外观。我构建了一个带有开关的小示例,该开关可以更改BoxView
的背景颜色,仅用于演示目的:
我已将一个DataTrigger
添加到BoxView.Triggers
,该触发器对开关.IsToggled
属性作出反应。如果设置为True
(请参阅值
属性),则设置器
将应用于BoxView
,背景色
将设置为矢车菊蓝
在你的情况下会是这样的
在这种情况下,不需要使用BindingContext
有效:
页面的默认颜色是什么?当开关未切换时,将设置什么颜色?白色和何时关闭应为白色,何时为黑色,何时为ONI如果您在显示设置器中设置断点,则在切换开关时它是否被击中?是的,但背景颜色不会更改xaml的前几行的显示方式(直到mc:Ignorable=“d”
行).但我需要更改内容页background@MathProblem请参阅我的编辑,我认为将解决方案传输到ContentPage
是微不足道的。@MathProblem添加了一个GIF,显示正在运行的触发器。不幸的是,MOV-to-GIF转换器最终搞糟了,在现实生活中它并没有那么起伏不定;)好的,很好,但是我需要数据绑定,因为颜色应该在不同的时间改变ContentPages@MathProblem请注意,设置Class1
的Display
属性也不会对其他页面产生影响,因为您使用
标记为每页创建一个实例。您必须在页面中注入一个实例,或者至少从代码隐藏中解析页面之间共享状态的单例。
public class Class1 : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private Color display;
public Color Display
{
get
{
return display;
}
set
{
if (display != value)
{
display = value;
NotifyPropertyChanged(nameof(Display));
}
}
}