C# 将图像值绑定到wpf和c中的路径#

C# 将图像值绑定到wpf和c中的路径#,c#,wpf,binding,C#,Wpf,Binding,我正在努力将值绑定到路径ImageSource。当我尝试设置新值时,我得到NullReferenceError。 我目前的代码是: 在MainWindow.xaml中,路径代码如下 <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" Mou

我正在努力将值绑定到路径ImageSource。当我尝试设置新值时,我得到NullReferenceError。 我目前的代码是:

在MainWindow.xaml中,路径代码如下

<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>
类,其中绑定值应为:

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));
            }
        }
    }

在代码隐藏中,您必须使用complete,包括
pack://application:,,,
前缀。您不应该指定
UriKind.Relative

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

编辑:您似乎混淆了一些事情。现在,不绑定ImageBrush的
ImageSource
属性可能更容易,而是直接在代码隐藏中设置它,如前一个问题中所示:

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

我是否需要替换此代码中的某些内容,因为我仍然得到NullReferenceError。如果我把我的RoundUI放在“UIs”里面,这有关系吗?我不知道,因为你还没有说“UIs”是什么。在如上所述的包URI中,“RoundUI”是被引用程序集的名称,“sadface.png”是该程序集根文件夹中的图像文件,它的生成操作必须设置为
Resource
。从何处获取NullReferenceException?这是否只是因为您没有分配
图像
字段?我注意到,我已经开始工作了,我查看了您提到的解决方案,还必须在xaml中向ImageBrush添加绑定。谢谢!:)
<Path x:Name="PPButton" ...
      MouseEnter="Path_MouseEnter_1" MouseLeave="Path_MouseLeave_1" >
    <Path.Fill>
        <ImageBrush/>
    </Path.Fill>
</Path>
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");
}