I am strugling to bind value to path ImageSource. I get NullReferenceError when I try to set new value. My current code is:

In MainWindow.xaml the Path code is following

<Path x:Name="PPButton" Data="M110,97 L155,123
        C135,150 135,203 153,227
        L112,255 
        C80,205 80,150 110,97" 
        Stretch="none" MouseEnter="Path_MouseEnter_1" MouseLeave="Path_MouseLeave_1" >
            <Path.Fill>
                <ImageBrush ImageSource="{Binding ImageSource}"/>
            </Path.Fill>
    </Path>

on MainWindow.xaml.cs where I get error, I commented behind Path_mouseEnter_1

Image image;
private void Path_MouseEnter_1(object sender, MouseEventArgs e)
        {
            image.ImageSource = new Uri("/RoundUI;component/sadface.png", UriKind.Relative); // This  "An unhandled exception of type 'System.NullReferenceException' occurred in RoundUI.exe"
        }

        private void Path_MouseLeave_1(object sender, MouseEventArgs e)
        {
            image.ImageSource = new Uri("/RoundUI;component/smileface.png", UriKind.Relative);
        }

Class, where binding value should take palce:

public class Image : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string title;
        private Uri imageSource;

        public Uri ImageSource
        {
            get
            {
                return imageSource;
            }
            set
            {
                imageSource = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("ImageSource"));
                }
            }
        }

        public void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
    }
有帮助吗?

解决方案

In code behind you have to use complete Pack URIs, including the pack://application:,,, prefix. And you should not specify UriKind.Relative.

private void Path_MouseEnter_1(object sender, MouseEventArgs e)
{
   image.ImageSource = new Uri("pack://application:,,,/RoundUI;component/sadface.png");
}

Edit: It seems that you are confusing a few things here. For now it might perhaps be easier not to bind the ImageBrush's ImageSource property, but instead set it directly in code behind, as shown in this answer to your previous question:

<Path x:Name="PPButton" ...
      MouseEnter="Path_MouseEnter_1" MouseLeave="Path_MouseLeave_1" >
    <Path.Fill>
        <ImageBrush/>
    </Path.Fill>
</Path>

Code behind:

private void Path_MouseEnter_1(object sender, MouseEventArgs e)
{
   var imageBrush = PPButton.Fill as ImageBrush;
   image.ImageSource = new Uri("pack://application:,,,/RoundUI;component/sadface.png");
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top