[英]UWP: How to bind a property from a base class in XAML
在過去的幾天里,我一直在嘗試為以下給定情況尋找解決方案。
我有一個包含不同顏色屬性的基礎 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"));
}
}
我的ColorPage
ViewModel 使用AppColors
class 作為其基礎:
public class ColorPageViewModel: AppColors
{
public static Brush ColorCustom { get; private set; }
public ColorPageViewModel ()
{
ColorCustom = new SolidColorBrush(U.Hex2Color("#ffff1234"));
}
}
在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>
運行應用程序時不使用與ColorBlack
屬性的綁定。 我期待它從基色 class 中檢索出來。
我可以通過聲明頁面資源並將其用作綁定源來解決問題,但這違背了使用顏色 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>
關於如何從基色 class 訪問屬性的任何建議?
關於如何從基色 class 訪問屬性的任何建議?
ColorBlack
不是視圖 model 的實例/本地屬性。
綁定到 static 屬性時使用{x:Bind}
:
<Grid Background="{x:Bind vm:ColorPageViewModel.ColorBlack}"></Grid>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.