繁体   English   中英

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

[英]Binding image value to path in wpf and c#

我正在努力将值绑定到路径 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>

在出现错误的 MainWindow.xaml.cs 上,我在 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);
        }

类,绑定值应该在这里:

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

在后面的代码中,您必须使用完整的Pack URI ,包括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>

后面的代码:

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM