UWP绑定。某事不正确

时间:2018-09-04 15:42:04

标签: c# xaml data-binding uwp

我是C#和UWP的新手。在读了许多天的正式Microsoft Dock和stackoverflow之后,我仍然不明白我在做什么错。

这是一个非常简单的测试应用。

我试图在单击时更改网格的背景。应用程序启动时,网格的背景为 bg-1.jpg 。单击后,属性 PicturePath 的值已更改,但Grid的背景未更改。 我想念什么?

这是一个简单的xaml页面

 <Page
    x:Class="Test.Views.StartPage"
    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"
    mc:Ignorable="d">
    <Grid PointerPressed="Grid_PointerPressed">
        <Grid.Background>
            <ImageBrush ImageSource="{Binding PicturePath, Mode=OneWay}" />
        </Grid.Background>
    </Grid>
  </Page>

背后的代码

public sealed partial class StartPage : Page
    {
        public StartPage()
        {
            this.InitializeComponent();
            DataContext = new {
                TestBackgroundClass.getInstance().PicturePath,
            };
        }

        private void Grid_PointerPressed(object sender, PointerRoutedEventArgs e)
        {
            TestBackgroundClass.getInstance().PicturePath = "ms-appx:///Assets/bg-2.jpg";
        }
    }

和单例课程

public class TestBackgroundClass : INotifyPropertyChanged
    {
        private static TestBackgroundClass instance;

        private string _picturePath { get; set; }

        public string PicturePath
            {
             get
               {
                return _picturePath;
               }
             set
               { 
                _picturePath = value;
                NotifyPropertyChanged();
               }
             }

        public TestBackgroundClass()
        {
            _picturePath = "ms-appx:///Assets/bg-1.jpg"
        }

        public static TestBackgroundClass getInstance()
        {
            if (instance == null) instance = new TestBackgroundClass();
            return instance;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

0 个答案:

没有答案