资源和x:Bind的奇怪行为

时间:2020-05-08 08:16:19

标签: c# uwp

我有以下代码:

<Page
    x:Class="BindingTest.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:BindingTest"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <Grid.Resources>
            <SolidColorBrush x:Key="ButtonForegroundPointerOver" Color="{x:Bind myColor}" />
            <SolidColorBrush x:Key="ButtonForegroundPressed" Color="Red" />

        </Grid.Resources>

        <Button>Click me!</Button>
    </Grid>
</Page>

// MainPage.xaml.cs
using Windows.UI.Xaml.Controls;

namespace BindingTest {
    public sealed partial class MainPage : Page {

        private string myColor = "Red";

        public MainPage() {
            this.InitializeComponent();
        }
    }
}

执行程序时,我得到一个System.NullReferenceException: Object reference not set to an instance of an object.

当我注释掉Resources块中的任一行(不管是哪一行)时,程序将毫无例外地启动。而且,当我用硬编码值(例如{x:Bind myColor}替换Green时,程序也可以工作,但是如上所述,当我只有{x:Bind myColor}的行时,程序也可以工作(另一则留言)。

什么会导致这种奇怪的行为,我该如何解决?

1 个答案:

答案 0 :(得分:0)

Page / Grid的资源中,您不能使用这种方式,它们可以是静态资源,因此只能使用{StaticResource xxx}。因此,您可以在App.xaml文件中定义颜色,如下所示作为静态资源。

<Application.Resources>
    <ResourceDictionary>
        <SolidColorBrush x:Key="myColor" Color="Red"/>
    </ResourceDictionary>
</Application.Resources>

然后,您可以通过这种方式使用自定义的颜色。

<Button Background="{StaticResource myColor}"/>
相关问题