简体   繁体   English

无法在代码后面更改图像源

[英]Can't change Image source in code behind

I am trying to change Image.Source in code behind. 我正在尝试在后面的代码中更改Image.Source When button clicked, Image.Source is modified in code behind and it supposed to display an image in windows. 当单击按钮时, Image.Source将在后面的代码中修改,并且应该在Windows中显示图像。 Unfortunately, it seems not working. 不幸的是,它似乎不起作用。 Can anyone give me an idea what the problem is? 谁能告诉我问题出在哪里? Thank you. 谢谢。

Here are my codes: 这是我的代码:

XML : XML

`<Grid Margin="0,0,-234,0">
        <Image Source="{Binding SourceName, Mode=TwoWay}" 
        Height="100" Width="100" Margin="201,69,661,151"/>
        <Button Margin="201,215,644,39" Click="Button_Click">show image</Button>
 </Grid>`

C# part: C#部分:

 private void Button_Click(object sender, RoutedEventArgs e)
    {
        Uri uri = new Uri(@"C:\localFTP\thisImage.jpg", UriKind.Absolute);

        BitmapImage i = new BitmapImage();
        i.BeginInit();
        i.UriSource = uri;
        i.EndInit();


        SourceName = i;
    }


    private ImageSource _sourceName;

    public ImageSource SourceName
    {
        get
        {
            return _sourceName;
        }
        set
        {
            _sourceName = value;
            OnPropertyChanged("SourceName");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

You don't seem to have the source of the binding set anywhere. 您似乎在任何地方都没有设置绑定的来源。

So either you set your MainWindow's DataContext, eg in the constructor like 因此,您可以设置MainWindow的DataContext,例如在类似

public MainWindow()
{
    InitializeComponent();   
    DataContext = this;
}

or you specify the binding source explicitly, eg by setting its RelativeSource: 或者您可以显式指定绑定源,例如通过设置其RelativeSource:

<Image Source="{Binding SourceName,
                RelativeSource={RelativeSource AncestorType=Window}}"/>

As a note, SourceName seems to be a strange name for a property of type ImageSource. 请注意, SourceName对于ImageSource类型的属性似乎是一个奇怪的名称。 It should better be named Source or ImageSource . 最好将其命名为SourceImageSource

It may also be worth to note that creating a BitmapImage actually requires less code than what you've shown in your question: 还可能需要注意的是,创建BitmapImage实际上需要的代码比问题中显示的要少:

private void Button_Click(object sender, RoutedEventArgs e)
{
    var uri = new Uri(@"C:\localFTP\thisImage.jpg");
    SourceName = new BitmapImage(uri);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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