[英]UWP: How to bind a property from a base class in XAML
For the past couple of days I have been tinkering trying to find a solution for the given situation below.在过去的几天里,我一直在尝试为以下给定情况寻找解决方案。
I have a base class AppColors
containing different color properties:我有一个包含不同颜色属性的基础 class
AppColors
:
public class AppColors
{
public static Brush ColorTransparent { get; private set; }
public static Brush ColorBlack { get; private set; }
public AppColors()
{
ColorTransparent = new SolidColorBrush(U.Hex2Color("#00ffffff"));
ColorBlack = new SolidColorBrush(U.Hex2Color("#ff000000"));
}
}
My ColorPage
ViewModel uses the AppColors
class as its base:我的
ColorPage
ViewModel 使用AppColors
class 作为其基础:
public class ColorPageViewModel: AppColors
{
public static Brush ColorCustom { get; private set; }
public ColorPageViewModel ()
{
ColorCustom = new SolidColorBrush(U.Hex2Color("#ffff1234"));
}
}
Inside the ColorPage
XAML I want to make a binding to the ColorBlack
property from the base color class.在
ColorPage
XAML 内部,我想从基色 class 绑定到ColorBlack
属性。
<Page
x:Class="MyApp.Pages.ColorPage"
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="using:MyApp"
xmlns:vm="using:MyApp.ViewModels"
mc:Ignorable="d">
<Page.DataContext>
<vm:ColorPageViewModel />
</Page.DataContext>
<!-- the property ColorBlack can not be retrieved, but no error is given -->
<Grid Background="{Binding ColorBlack}"></Grid>
</Page>
The binding to the ColorBlack
property is not used when I run the application.运行应用程序时不使用与
ColorBlack
属性的绑定。 I was expecting it to be retrieved from the base color class.我期待它从基色 class 中检索出来。
I can fix the problem by declaring a page resource and use that as my source for the binding, but that defeats the whole purpose of using the color class as a base.我可以通过声明页面资源并将其用作绑定源来解决问题,但这违背了使用颜色 class 作为基础的全部目的。
<Page.Resources>
<local:AppColors x:Key="AppColors" />
</Page.Resources>
<Page.DataContext>
<vm:ColorPageViewModel />
</Page.DataContext>
<!-- the property ColorBlack works now! -->
<Grid Background="{Binding ColorBlack, Source={StaticResource AppColors}}"></Grid>
Any advice on how to access the properties from the base color class?关于如何从基色 class 访问属性的任何建议?
Any advice on how to access the properties from the base color class?
关于如何从基色 class 访问属性的任何建议?
ColorBlack
is not an instance/local property of the view model. ColorBlack
不是视图 model 的实例/本地属性。
Use {x:Bind}
when you bind to static properties:绑定到 static 属性时使用
{x:Bind}
:
<Grid Background="{x:Bind vm:ColorPageViewModel.ColorBlack}"></Grid>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.